Stuck accessing 2d Map's inner elements

I'm stuck accessing a 2D map
How do I retrieve data out of the inner map?

map <string, map <int, class> > myMap

How do I retrieve the int and class for each string?

When I set up and iterator it, I get a std::pair.
it->second should yield a pair aswell because it points to map <int, class>
but I can't make a std::pair out of it->second.

it->second isn't recognized as a pair.



Last edited on
I made an example for you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <map>

using namespace std;

class point
{
public:
	point() : _X(0), _Y(0) {}
	point(const int& x, const int& y) : _X(x), _Y(y) {}

	int get_x() const{
		return _X;
	}

	int get_y() const{
		return _Y;
	}
private:
	int _X;
	int _Y;
};

int main()
{
	map<string, pair<int, point> > mymap;

	point p1(1, 1);
	point p2(2, 2);
	point p3(3, 3);

	mymap.insert(pair<string, pair<int, point> >("point 1", pair<int, point>(1, p1)));
	mymap.insert(pair<string, pair<int, point> >("point 2", pair<int, point>(2, p2)));
	mymap.insert(pair<string, pair<int, point> >("point 3", pair<int, point>(3, p3)));

	cout << "Contents of mymap:" << endl;

	for(map<string, pair<int, point> >::iterator iter = mymap.begin(); iter != mymap.end(); iter++)
	{
		cout <<(*iter).first << ": X = " << (*iter).second.second.get_x() << "\tY = " << (*iter).second.second.get_y() << endl;
	}

	cin.get();
	return 0;
}


As you can see, you can retrieve the element in this case with an iterator to mymap, (*iter).second.second.get_x(), second.second because the first second points to pair<string, point> and the other second points to point.

An easier way to retrive directly the element you want is using overloaded operator[] from map:

Eg:

mymap[0].second.get_x()

It can throw an exception if the element isn't set.
You just saved my life. I owe you one.
Topic archived. No new replies allowed.