C ++函数插入模板地图 [英] C++ function to insert to template map
问题描述
继续我上一个问题 C ++模板类映射我已经实现了这个功能来插入一些值。此功能为一系列键插入相同的值。如果地图中存在密钥,则应覆盖旧值。功能最终是否正确有效?你能建议一个更好的方法来实现吗?
Continuing from my last question C++ template class map I have implemented the function to insert some values. This function inserts the same value for a range of keys. If the key exists in the map it should overwrite the old values. Is the function eventually correct and efficient? Could you suggest a better way to implement it?
void insert_ToMap( K const& keyBegin, K const& keyEnd, const V& value)
{
if(!(keyBegin < keyEnd))
return;
const_iterator it;
for(int j=keyBegin; j<keyEnd; j++)
{
it = my_map.find(j);
if(it==my_map.end())
{
my_map.insert(pair<K,V>(j,value));
}
else
{
my_map.erase(it);
my_map.insert(pair<K,V>(j, value));
}
}
}
我尝试:
int main()
{
template_map<int,int> Map1 (10);
Map1.insert_ToMap(3,6,20);
Map1.insert_ToMap(4,14,30);
Map1.insert_ToMap(34,37,12);
for (auto i = Map1.begin(); i != Map1.end(); i++)
{
cout<< i->first<<" "<<i->second<<std::endl;
}
}
推荐答案
插入键是否存在:
typedef std:::map<K, V> map_type;
std::pair<typename map_type::iterator, bool> p
= my_map.insert(std::pair<K const &, V const &>(key, new_value));
if (!p.second) p.first->second = new_value;
这个结构充分利用了 insert
已执行 find()
,如果插入失败,您可以立即使用生成的迭代器覆盖映射值。
This construction takes advantage of the fact that insert
already performs a find()
, and if the insertion fails, you can immediately use the resulting iterator to overwrite the mapped value.
这里有一定的隐藏成本:插入总是使元素的副本,无论其实际是否成功。为了避免这种情况,我们可以使用 lower_bound()
稍微更详细的方法来搜索所声明的密钥,同时为新元素提供正确的插入位置: p>
There is a certain hidden cost here: The insertion always makes a copy of the element, whether or not it actually succeeds. To avoid even that, we can use a slightly more verbose approach using lower_bound()
to search for the purported key and simultaneously provide the correct insertion position for the new element:
typename map_type::iterator it = my_map.lower_bound(key);
if (it == my_map.end() || it->first != key)
{
my_map.insert(it, std::pair<K const &, V const &>(key, new_value)); // O(1) !
}
else
{
it->second = new_value;
}
双参数版本的 insert()
如果插入提示(第一个参数中的迭代器)是插入的正确位置,这是正确的,这就是 lower_bound()
提供。
The two-argument version of insert()
operates in constant time if the insertion hint (the iterator in the first argument) is the correct position for the insertion, which is precisely what lower_bound()
provides.
这篇关于C ++函数插入模板地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!