我在 this 听说过关于 C++ 关联容器的讲座,如果你有这样的 map :
map<string,string> m;
它的元素是这样的类型:
pair<const string,string>
我有一个代表电话号码列表的小类
PhoneList operator+(const PhoneList & g){
PhoneList copy(*this);
for(map<string,string>::const_iterator it = g.datos.begin(); it != g.datos.end(); ++it){
copy.insert(*it);
}
return copy;
}
问题是插入方法有以下标题:
pair<map<string,string>::iterator,bool> insert(pair<string,string> p)
显然,我正在将一对变成一对。
我只想知道为什么会这样。 const string 和 string 之间有转换吗?
最佳答案
您的代码有效的原因有两个。首先,因为你正在传递 insert
() 的参数按值:
pair<map<string,string>::iterator,bool> insert(pair<string,string> p)
如果您改为通过引用传递参数,您的代码将无法编译:
pair<map<string,string>::iterator,bool> insert(const pair<string,string> &p)
按值传递非平凡参数通常效率较低,但因为在这里您按值传递此参数,所以该参数本质上是复制构造的。这是第二个原因。您最终使用以下 std::pair
模板构造函数:
template<class U, class V> pair(const pair<U, V>& p);
Requires: is_constructible<first_type, const U&>::value is true and
is_constructible<second_type, const V&>::value is true.
Effects: Initializes members from the corresponding members of the
argument.
这就是您能够编译代码的原因。总而言之,此模板构造函数允许 std::pair<A, B>
由 std::pair<C, D>
构建,不同的类,如果 A 可以从 C 构造,B 可以从 D 构造。在您的情况下,A、B 和 D 是 std::string
, C 是 const std::string
.显然构建一个新的 std::string
没有问题。来自其他一些std::string
,它是一个普通的复制构造函数。
关于c++ - C++ map 中的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32533059/