为什么std :: map没有insert类型的插入函数(key&k,val&v)

0xh*_*ker 4 c++ std c++-standard-library c++11

为什么不std::map支持如下插入:

std::map<obj1, obj2> map_int;

void insert_map(obj1 &key, obj2 &val)
{
    map_int.insert(key, val);
}
Run Code Online (Sandbox Code Playgroud)

我知道上面的内容不正确.我想知道是什么阻止了这样设计插入函数.它比创建一对IMO更直观.

Bar*_*rry 8

它被称为emplace():

std::map<std::string, std::string> m;

// uses pair's template constructor
m.emplace("d", "ddd");
Run Code Online (Sandbox Code Playgroud)

  • @ 0xhacker因为在引擎盖下,`std :: map`的`value_type`是`std :: pair <first_type,second_type>`. (4认同)
  • @ 0xhacker,可能是为了与所有其他STL容器保持一致,需要插入`value_type`.通用代码受益于此一致性.但是,如果用例足够大,可能会有额外的过载. (3认同)