Oct 21, 2013 at 5:10pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
map<int ,int > myMap;
map<int ,int >::iterator iter;
myMap.insert(pair<int ,int >(1,2));
myMap.insert(pair<int ,int >(3,4));
myMap.insert(pair<int ,int >(5,6));
for (iter = myMap.begin() ;iter != myMap.end() ;iter++)
{
cout << iter->first << " " << iter->second << endl;
}
return 0;
}
In this example is There a way to get the first and second values of map without using the iterator ?
Thanks in advance
Last edited on Oct 21, 2013 at 5:13pm UTC
Oct 21, 2013 at 5:32pm UTC
Thanks @giblit for the repley
I tried that ,and does not work
PS : I compile with code::blocks
Oct 21, 2013 at 5:38pm UTC
Sorry I didn't mean i.first/second I meant myMap.at(i).first/second or myMap[i].first/second.
Oct 21, 2013 at 5:59pm UTC
I would just use iterators then. That's what I use haven't really tried other ways. The first/second are functions from the pair anyways.
Oct 21, 2013 at 6:19pm UTC
To step through a map, you must use an iterator. Maps do not allow indexed access. You could access all elements with the [] operator, or the find() function... but only if you already know all the keys.
The only other way would be to remove items from the map as you examine them (but that would be ridiculous).
Oct 21, 2013 at 6:40pm UTC
Ah yes... JLBorges is correct. That does actually allow you to not use iterators. I hadn't thought of it because it "hides" the iterators from you.
Oct 21, 2013 at 9:47pm UTC
So I think I conculde this topic by saying that in c++98 the only way is by iterator but in c++11 we can use the magnificent way of @JLBorges
am I right?