Professional C__ - Marc Gregoire [209]
class Data
{
public:
Data(int val = 0) { mVal = val; }
int getVal() const { return mVal; }
void setVal(int val) { mVal = val; }
protected:
int mVal;
};
int main()
{
map return 0; } Code snippet from MapBasics\MapInsert.cpp maps also support the C++11 uniform initialization mechanism as shown in the following example: map {"Marc G.", 123}, {"Zulija N.", 456}, {"John D.", 369} }; Code snippet from MapBasics\MapUniformInit.cpp Inserting Elements Inserting an element into the sequential containers such as vector and list always requires you to specify the position at which the element is to be added. The map, along with the other associative containers, is different. The map internal implementation determines the position in which to store the new element; you need only to supply the key and the value. map and the other associative containers do provide a version of insert() that takes an iterator position. However, that position is only a “hint” to the container as to the correct position. The container is not required to insert the element at that position. When inserting elements, it is important to keep in mind that maps support so-called “unique keys”: Every element in the map must have a different key. If you want to support multiple elements with the same key, you must use multimaps, which are described later. There are two ways to insert an element into the map: one clumsy and one not so clumsy. The insert() Method The clumsy mechanism to add an element to a map is the insert() method, but it has the advantage of allowing you to detect if the key already exists. One problem is that you must specify the key/value pair as a pair object. The second problem is that the return value from the basic form of insert() is a pair of an iterator and a bool. The reason for the complicated return value is that insert() does not overwrite an element value if one already exists with the specified key. The bool element of the returned pair specifies whether the insert() actually inserted the new key/value pair or not. The iterator refers to the element in the map with the specified key (with a new or old value, depending on whether the insert succeeded or failed). Continuing the map example from the previous section, you can use insert() as follows: map auto ret = dataMap.insert({1, Data(4)}); // Using C++11 initializer_list if (ret.second) { cout << "Insert succeeded!" << endl; } else { cout << "Insert failed!" << endl; } ret = dataMap.insert(make_pair(1, Data(6))); if (ret.second) { cout << "Insert succeeded!" << endl; } else { cout << "Insert failed!" << endl; } Code snippet from MapBasics\MapInsert.cpp The output of the program is: Insert succeeded! Insert failed! If your compiler does not support the C++11 auto keyword, you have to declare the correct type for ret yourself as follows: pair