How to insert pair into map
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));
Assuming you're using C++11 or later, the best approach is probably:
object * myObject = // get an object somehow
myMap.emplace({1,2}, myObject);
For maps, emplace
can be thought of as a version of insert
that takes the key and value as separate arguments (it can actually take any combination of arguments that the corresponding pair
type's constructors can take). In addition to being syntactically cleaner, it's also potentially more efficient than make_pair
, because make_pair
will usually produce an output whose type doesn't precisely match the value_type
of the container, and so it incurs an unnecessary type conversion.
I used to recommend this, which also only works in C++11 or later:
object * myObject = // get an object somehow
myMap.insert({{1,2}, myObject});
This avoids the slightly surprising use of emplace
, but it formerly didn't work if the key or value type are move-only (e.g. unique_ptr
). That's been fixed in the standard, but your standard library implementation may not have picked up the fix yet. This might also theoretically be slightly less efficient, but in a way that any halfway decent compiler can easily optimize away.
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
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.
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.