继续我的上一个问题C++ template class map我已经实现了插入一些值的功能。此函数为一系列键插入相同的值。如果键存在于映射中,它应该覆盖旧值。该函数最终是否正确且高效?您能提出更好的实现方法吗?
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()
的事实,如果插入失败,您可以立即使用生成的迭代器来覆盖映射的值。
这里有一定的隐藏成本:插入总是会复制元素,无论它是否真正成功。为了避免这种情况,我们可以使用稍微更详细的方法,使用 lower_bound()
来搜索所谓的键,同时为新元素提供正确的插入位置:
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()
提供。
关于用于插入模板映射的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415718/