In practice, if we do so at all, we use an associative container with the algorithms either as the source sequence or as a destination. For example, we might use the generic copy algorithm to copy the elements from an associative container into another sequence. Similarly, we can call inserter to bind an insert iterator to an associative container. Using inserter, we can use the associative container as a destination for another algorithm.
The insert members (Table 11.4(overleaf)) add one element or a range of elements. Because map and set(and the corresponding unordered types) contain unique keys, inserting an element that is already present has no effect:
set
set2.insert(ivec.cbegin(), ivec.cend()); // set2 has four elements
set2.insert({1,3,5,7,1,3,5,7}); // set2 now has eight elements
Adding Elements to a map:
// four ways to add word to word_count
word_count.insert({word, 1});
word_count.insert(make_pair(word, 1));
word_count.insert(pair
word_count.insert(map
Testing the Return from insert:
// more verbose way to count number of times each word occurs in the input
map
string word;
while (cin >> word) {
// inserts an element with key equal to word and value 1;
// if word is already in word_count, insert does nothing
auto ret = word_count.insert({word, 1});
if (!ret.second) // word was already in word_count
++ret.first->second; // increment the counter
}
Adding Elements to multiset or multimap
Because keys in a multi container need not be unique, insert on these types always inserts an element:
// adds the first element with the key Barth, John
authors.insert({"Barth, John", "Sot-Weed Factor"});
// ok: adds the second element with the key Barth, John
authors.insert({"Barth, John", "Lost in the Funhouse"});
For the containers that allow multiple keys, the insertoperation that takes a single element returns an iterator to the new element. There is no need to return a bool, because insert always adds a new element in these types.
Table 11.5. Removing E