tags:

views:

521

answers:

2

I have the following map structure: map < pair < int,int >, object* > and I wish to insert into it. How would I do it since I am trying to insert a pair and an object and I must make a pair out of this. Should I create a new pair using make_pair() out of the pair and object that I have? If so, could you please let me know how to do this?

Thanks

+5  A: 
object * myObject = // get an object somehow
myMap.insert(std::make_pair(std::make_pair(1,2), myObject));

or

typedef map<pair<int, int>, object *> MapType;
object * myObject = // get an object somehow
myMap.insert(MapType::value_type(std::make_pair(1,2), myObject));
Nick Meyer
I used your first suggestion - nice and concise. Thanks so much!
Myx
If you're using this a lot in your code you might want to wrap the map up in a class with an insert (pair, object) function for readability.
Tom Smith
+1  A: 

There are two ways:

typedef std::map<int,Object> map_t;
map_t map;
Object obj;

std::pair<map_t::iterator, bool> result = map.insert(std::make_pair(1,obj)); // 1

map[1] = obj; // 2
  1. Only works if the key is not already present, the iterator points to the pair with the key value and the bool indicates if it has been inserted or not.

  2. Easier, but if it does not already exist the object is first default constructed and then assigned instead of being copy constructed

If you don't have to worry about performance, just choose by whether or not you wish to erase the previous entry.

Matthieu M.
Correct, but the question asked about a map with a key type which is also a pair.
Nick Meyer
I fail to see the dependence. `sed s/1/std::make_pair(1,1)/g` and a suitably defined `map_t`. It does not change the comments or anything, I just prefer to demonstrate with simple concepts to help focus on the important points rather than hiding them in the crowd.
Matthieu M.