Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map initializer list constructor

The C++ standard defines a std::map constructor using a 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}.

However, I was unable to find anything in the C++ standard regarding this.

like image 612
tobspr Avatar asked Dec 16 '16 12:12

tobspr


People also ask

Does initializer list call constructor?

An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above). In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.

What is a constructor initializer list?

Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.

Is constructor same as initializer?

Constructor is a special non-static member function of a class that is used to initialize objects of its class type. In the definition of a constructor of a class, member initializer list specifies the initializers for direct and virtual bases and non-static data members.


1 Answers

N4296 (~C++14)

Table 102 - Associative container requirements

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

Then from above in the table, for the iterator ctor:

Effects: Constructs an empty container and inserts elements from the range [i, j) into it; uses c as a comparison object.

and

i and j satisfy input iterator requirements and refer to elements implicitly convertible to value_type, [i,j) denotes a valid range,

Note that "and inserts elements" here is not marked up to indicate the insert function, but I suppose we may interpret it that way. Also note that i and j are input iterators, so must be traversed in order.

.

(It is slightly harder to find this information, because the equivalent tables all have

il designates an object of type 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.)

like image 161
BoBTFish Avatar answered Sep 19 '22 15:09

BoBTFish