Inserting elements

suggest change

insert adds an element to a std::map only if its key is not already present. Given for example:

std::map<std::string, std::size_t> fruits_count;
fruits_count.insert({"grapes", 20});
fruits_count.insert(std::make_pair("orange", 30));
fruits_count.insert(std::pair<std::string, std::size_t>("banana", 40));
fruits_count.insert(std::map<std::string, std::size_t>::value_type("cherry", 50));

The insert() function returns a pair consisting of an iterator and a bool value:

The following method can be used to combine insertion and searching operation:

auto success = fruits_count.insert({"grapes", 20});
if (!success.second) {           // we already have 'grapes' in the map
    success.first->second += 20; // access the iterator to update the value
}
fruits_count["apple"] = 10;

While simpler, it prevents the user from checking if the element already exists. If an element is missing, std::map::operator[] value-initializes the mapped type and then assigns the supplied value.

fruits_count.insert({{"apricot", 1}, {"jackfruit", 1}, {"lime", 1}, {"mango", 7}});
std::map<std::string, std::size_t> fruit_list{ {"lemon", 0}, {"olive", 0}, {"plum", 0}};
fruits_count.insert(fruit_list.begin(), fruit_list.end());

Example:

std::map<std::string, std::size_t> fruits_count;
std::string fruit;
while(std::cin >> fruit){
    // insert an element with 'fruit' as key and '1' as value
    // (if the key is already stored in fruits_count, insert does nothing)
    auto ret = fruits_count.insert({fruit, 1});
    if(!ret.second){            // 'fruit' is already in the map 
        ++ret.first->second;    // increment the counter
    }
}

A single insertion is logarithmic in the size of the map.

emplace constructs the element in place. insert can take a pair built by std::make_pair:

std::map<std::string, int> runs;
runs.emplace("Babe Ruth", 714);
runs.insert(std::make_pair("Barry Bonds", 762));

If we know where the new element will be inserted, then we can use emplace_hint() to specify an iterator hint. If the new element is inserted just before hint, the insertion is amortized constant time. Otherwise it behaves in the same way as emplace():

std::map<std::string, int> runs;
auto it = runs.emplace("Barry Bonds", 762).first; // iterator to the inserted element
// the next element will be before "Barry Bonds", so it is inserted before 'it'
runs.emplace_hint(it, "Babe Ruth", 714);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents