简体   繁体   English

std :: map初始化列表构造函数

[英]std::map initializer list constructor

The C++ standard defines a std::map constructor using a std::initializer_list : C ++标准使用std::initializer_list定义了一个std::map构造std::initializer_list

map( std::initializer_list<value_type> init, const Allocator& );

However, where is defined what happens if the initializer list contains duplicate keys? 但是,在哪里定义了初始化程序列表包含重复键时会发生什么? Is the first key choosen, or the last? 是第一个选择键还是最后一个? For example: 例如:

std::map<std::string, int> my_map {
  {"a", 1}, 
  {"a", 2}
};

In practice, it seems it behaves like insert() , so that the map will now contain {a: 1}. 在实践中,它看起来像insert() ,因此地图现在将包含{a:1}。

However, I was unable to find anything in the C++ standard regarding this. 但是,我无法在C ++标准中找到任何关于此的内容。

N4296 (~C++14) N4296(~C ++ 14)

Table 102 - Associative container requirements 表102 - 关联容器要求

X(il); | | Same as X(il.begin(), il.end()) . X(il.begin(), il.end())相同X(il.begin(), il.end())

Then from above in the table, for the iterator ctor: 然后从表中的上方,对于迭代器ctor:

Effects: Constructs an empty container and inserts elements from the range [i, j) into it; 效果:构造一个空容器并将范围[i, j)元素插入其中; uses c as a comparison object. 使用c作为比较对象。

and

i and j satisfy input iterator requirements and refer to elements implicitly convertible to value_type , [i,j) denotes a valid range, ij满足输入迭代器要求并引用可隐式转换为value_type元素, [i,j)表示有效范围,

Note that "and inserts elements" here is not marked up to indicate the insert function, but I suppose we may interpret it that way. 请注意,此处的“和插入元素” 标记为表示insert函数,但我想我们可以这样解释它。 Also note that i and j are input iterators, so must be traversed in order. 另请注意, ij输入迭代器,因此必须按顺序遍历。

.

(It is slightly harder to find this information, because the equivalent tables all have (找到这些信息稍微困难一些,因为相同的表格都有

il designates an object of type initializer_list<value_type> il指定类型为initializer_list<value_type>的对象

above them, so can be found by searching for initializer_list , but for this table the word is split over two lines, with a hyphen at the break.) 在它们之上,所以可以通过搜索initializer_list找到,但是对于这个表,这个单词被分成两行,在断点处有一个连字符。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM