c++ - C++ map 中的元素类型

标签 c++ dictionary types stl

我在 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/

相关文章:

c++ - 将数据插入文件中的特定位置而不覆盖c++

c++ - MongoCxx 3.1.0 如何关闭连接?

c++ - 只传递第二个模板参数的方法

c++ - 有趣的 C++ 运算符重载问题

python - 将字符串转换为dicts python列表的列表

python - 将文本文件的行添加到字典

python - 检查搁架中是否存在 key 的最快方法

python - 如何从数据库数据中取平均值?类型错误 : unsupported operand type(s) for/: 'Decimal' and 'float'

types - Coq 中的类型封装

python - 将元组 append 到列表 - 两种方式有什么区别?