advance problem 01

closed account (28poGNh0)
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
You can use a normal for loop. Then do i.first , i.second

1
2
3
4
for( int i = 0; i < MAPSIZE; ++i )
{
   cout << i.first << ' ' << i.second << endl;
}
closed account (28poGNh0)
Thanks @giblit for the repley
I tried that ,and does not work

PS : I compile with code::blocks
Sorry I didn't mean i.first/second I meant myMap.at(i).first/second or myMap[i].first/second.
closed account (28poGNh0)
Does not work either
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.
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).
Prefer using a range based loop to iterate through all elements of a container.

1
2
3
4
5
6
7
8
9
#include <iostream>
#include <map>

int main()
{
    std::map<int,int> map { {1,2}, {3,4}, {5,6} } ;

    for( const auto& pair : map ) std::cout << pair.first << ' ' << pair.second << '\n' ;
}

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.
closed account (28poGNh0)
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?
Topic archived. No new replies allowed.