C++ 函数插入到模板映射

arj*_*soh 2 c++ templates dictionary

继续我的上一个问题C++ 模板类映射,我已经实现了插入一些值的函数。此函数为一系列键插入相同的值。如果键存在于地图中,它应该覆盖旧值。该功能最终是否正确且有效?你能提出一个更好的方法来实现它吗?

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));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试:

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; 
  }
}
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 5

要插入密钥是否存在:

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;
Run Code Online (Sandbox Code Playgroud)

这种构造利用了insert已经执行 a的事实,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;
}
Run Code Online (Sandbox Code Playgroud)

insert()如果插入提示(第一个参数中的迭代器)是插入的正确位置,则的双参数版本在恒定时间内运行,这正是所lower_bound()提供的。