开发者

How to insert pair into map

开发者 https://www.devze.com 2022-12-21 01:53 出处:网络
I have the following map structure: map < pair < int,int >, object* > and I wish to insert into it.

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 开发者_JAVA技巧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?


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
  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.


int a=10,b=20;

map < pair < int,int >, int > m;

pair < int,int >numbers = make_pair(a,b);

int sum=a+b;

m[numbers]=sum;

Our map will have its key as pairs of numbers.We can access the integer values of pair variable using dot(.) operator.

0

精彩评论

暂无评论...
验证码 换一张
取 消