std :: map insert或std :: map find? [英] std::map insert or std::map find?

查看:161
本文介绍了std :: map insert或std :: map find?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您要保留现有条目的地图。 20%的时间,您要插入的条目是新数据。是否有优势做std :: map :: find然后std :: map :: insert使用返回的迭代器?

解决方案

答案是你不做。相反,您要执行有效STL 的第24项建议的操作( Scott Meyers

  typedef map< int,int& MapType; //你的地图类型可能不同,只是改变typedef 

MapType mymap;
//添加元素到这里
int k = 4; //假设我们正在搜索等于4的键
int v = 0; //假设我们想要的值为0与4的键相关联

MapType :: iterator lb = mymap.lower_bound(k);

if(lb!= mymap.end()&&!(mymap.key_comp()(k,lb-> first)))
{
/ / key已经存在
//更新lb-> second如果你关心
}
else
{
//键在地图中不存在
//将其添加到映射
mymap.insert(lb,MapType :: value_type(k,v)); //使用lb作为提示插入,
//可以避免另一个查找
}


Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the record was or was not inserted?

解决方案

The answer is you do neither. Instead you want to do something suggested by Item 24 of Effective STL by Scott Meyers:

typedef map<int, int> MapType;    // Your map type may vary, just change the typedef

MapType mymap;
// Add elements to map here
int k = 4;   // assume we're searching for keys equal to 4
int v = 0;   // assume we want the value 0 associated with the key of 4

MapType::iterator lb = mymap.lower_bound(k);

if(lb != mymap.end() && !(mymap.key_comp()(k, lb->first)))
{
    // key already exists
    // update lb->second if you care to
}
else
{
    // the key does not exist in the map
    // add it to the map
    mymap.insert(lb, MapType::value_type(k, v));    // Use lb as a hint to insert,
                                                    // so it can avoid another lookup
}

这篇关于std :: map insert或std :: map find?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C/C++开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆