更准确地说,我想知道有多少std::pair
模板构造函数调用是在以下代码片段中进行的:一个(对于 std::pair<const KeyType, ValueType>
)或两个(第一个用于 std::pair<KeyType, ValueType>
的 make_pair
,然后第二个由 std::pair<const KeyType, ValueType>
调用 insert
)?
std::map<KeyType, ValueType> m;
void addToMap(const KeyType& key)
{
ValueType val = someCalculation(key);
m.insert(std::make_pair(key, val));
}
最佳答案
制作了两份,如std::make_pair(key,val)
返回 std::pair<KeyType, ValueType>
而不是 std::pair<const KeyType, ValueType>
, 所以需要复制。
你可以强制std::make_pair
给出正确的类型:
m.insert(std::make_pair<const KeyType, ValueType>(key, val));
但是你也可以构建一个 std::pair
直接:
m.insert(std::pair<const KeyType, ValueType>{key, val});
m.insert(decltype(m)::value_type(key,val));
但是,最好的选择是避免创建临时 std::pair
首先使用 emplace
:
m.emplace(key, val);
关于c++ - const引用传递的参数在函数中是否完全充当了const类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32759399/