I have a question about std::map structure:
this code fragment works correctly:
map<string,int> mappa;
int main(int argc, char** argv) {
mappa["b"]=1;
mappa["a"]=2;
for(std::map<string,int>::iterator it=mappa.begin();it!=mappa.end();++it )
{
cout<<it->first<<"\n";
}
return 0;
}
output:
a
b
but if I do:
map<string,int> mappa;
std::map<string,int> getList(){
return mappa;
}
int main(int argc, char** argv) {
mappa["b"]=1;
mappa["a"]=2;
for(std::map<string,int>::iterator it=getList().begin();it!=getList().end();++it )
{
cout<<it->first<<"\n";
}
return 0;
}
my output is just
b
why?
Thanks!
You are calling
getListmultiple times. Each time it creates a new map using the copy constructor.You such do this:
I am assuming that you require a copy.