简体   繁体   English

C ++中map_instance [key]与map_instance.find(key)之间的区别

[英]difference between map_instance[key] vs. map_instance.find(key) in c++

I have a map defined as 我有一张地图定义为

static map<unsigned int, deque<FOO_STRUCT*> > CV_MAP; 

and I was wondering if one method was better than the other between: 我想知道一种方法是否比另一种更好:

map_instance[key] vs. map_instance.find(key).

map_instance[key] will default construct a new value for the key key if it is not present. map_instance[key]将默认构造一个新的值的键key ,如果它不存在。

As in, it will call deque<FOO_STRUCT*> 's constructor if key is not present, and return the newly constructed deque<FOO_STRUCT*> . deque<FOO_STRUCT*>如果不存在key ,它将调用deque<FOO_STRUCT*>的构造函数,并返回新构造的deque<FOO_STRUCT*>

Using the find member function will not construct a new value for the given key-- when the key is absent, it will just return an iterator that points to CV_MAP.end() . 使用find成员函数不会为给定的键构造新的值-当键不存在时,它将仅返回指向CV_MAP.end()的迭代器。

Use what's appropriate for your use case. 使用适合您的用例的内容。

map_instance[key] -返回引用 (在需要之前,构造新元素) map_instance.find(key) -返回迭代器

map_instance[key] can be preferred where all you care is put the key with default initialization into the map, if not present, or do something with it if present. map_instance[key]默认初始化的密钥放入地图(如果不存在)或对其进行一些处理,则可以使用map_instance[key]作为首选。

Consider a case where you want to store count of each element in an array. 考虑一种情况,您希望将每个元素的计数存储在数组中。

for(auto x : array){
   map_instance[x]++;  //no need to find here at first. 
}

As you can see it really simplifies your code, and gets rid of if-else clause. 如您所见,它确实简化了代码,并摆脱了if-else子句。

for(auto x : array){
   if ( map_instance.find(key) == map_instance.end() ) {
      map_instance[x] = 0;
   }
   else{
      map_instance[x]++;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM