Map::using size() and looping [closed]
//employee is class with public members salary and nname
int main()
{
map<int,employee> employees;
employee e1;
strcpy(e1.nname,"aaa");
e1.salary=25000;
employee e2;
strcpy(e2.nname,"ccc");
e2.salary=26000;
employees[1]=e1;
employees[2]=e2;
employee e3;
strcpy(e3.nname,"bbb");
e3.salary=26000;
employees[5]=e3;
employee ee;
cout<<employees.size()<<endl;
for(int i=0;i<employees.size();i++)
{
ee=employees[i];
cout<<ee.nname<<endl;
}
o/p: 3 - //so i=3 displays employees[0],1,2,3
aaa - //i=
ccc -
- //2 blank lines
- // <---why blank line cming ,ok cause no data but why it
bbb - //executed 4th and 5th time and we got
// employees[5] ----- bbb?????
//when i printed value of"i" i got from 0 to 5!!!
--------------
can any1 explain thanx in advance
You are displaying employees[i]
, where i= 0,1,2,3,4,5
.
Why are you displaying 6 entries if employees.size() == 3
prior to entering the for-loop?
The answer is, that when i==0
, you are adding an entry to the map at employees[0]
.
(This is because map::operator[]
returns a reference, and if the entry does not exist, it creates one).
So now, employees.size()
equals 4.
Calling employees[1],[2]
does not alter the map, but because the size is 4, you are also accessing employees[3]
, which in turn adds an entry to the map (and so on for employees[4]
).
This stops when you reach employees[5]
, because it exists in the map and the map does not grow anymore.
If you want to iterate through the map entries, use an iterator.
map<int, employee>::iterator it;
for (it = employees.begin(); it != employees.end(); ++it)
{
ee = it->second;
cout<< ee.nname << endl;
}
PS- Please, make your code readable.
OK, let's try this with a more controlled example:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map<int,string> db;
db[1] = string("index = 1");
db[2] = string("index = 2");
db[5] = string("index = 5");
for (size_t i = 0; i < db.size(); i++)
{
cout << i << " : " << db[i] << endl;
cout << "size is : " << db.size() << endl;
}
return 0;
}
Now, the problem here is that when you access the db[0]
, db[3]
and db[4]
, you are actually adding elements into the map.
0 :
size is : 4
1 : index = 1
size is : 4
2 : index = 2
size is : 4
3 :
size is : 5
4 :
size is : 6
5 : index = 5
size is : 6
You may also have another problem. Your class employee might have a broken default constructor, that isn't initializing the string attribute correctly.
精彩评论