在地图和恒常性中插入一对

Inserting a pair into the map and constness?

本文关键字:插入 常性中 地图      更新时间:2023-10-16

在下面的样本中,是否有任何正当的理由为什么人们更喜欢一对而不是另一对而不是第三对而不是第四对?

map<const int, int> test;
test.insert(const pair<const int, int>(3, 9));
test.insert(const pair<int, int>(3, 9));
test.insert(pair<int, int>(3, 9));
test.insert(pair<const int, int>(5, 9));

基本上是的。哑编译器将在此代码中调用一个额外的转换构造函数

test.insert(pair<const int, int>(5, 9));

但是优化编译器将使其与其他替代方案相同。

我只问,谁会想写这样的代码?通常,我会写test.insert(std::make_pair(3, 9)),不会在乎。

最后 2 对插入地图时没有区别。map中的键默认是常量,只需使用make_pair函数即可