Search code examples
c++c++11verbositycode-formatting

Decreasing verbosity: inserting elements into map


I've been getting familiar with C++11 lately, and the auto keyword is great! Typing:

for (auto bar : bars) {

is oh-so satisfying. Keeps code readable and pretty. What still feels like it stops all your momentum is the following:

foo.insert(std::pair<std::string, bar>("soVerbose", baz));

// As opposed to simply:

foo.insert("soVerbose", baz);

Is there a good reason it is the way it is? And is there some neat way of making it less verbose? I know the [] operator can be used for inserting elements into maps, but the functionality is slightly different.


Solution

  • Use the emplace function:

    #include <iostream>
    #include <utility>
    
    #include <map>
    
    int main()
    {
        std::map<std::string, std::string> m;
    
        // uses pair's copy-constructor
        m.emplace(std::make_pair(std::string("a"), std::string("a")));
    
        // uses pair's converting copy constructor
        m.emplace(std::make_pair("b", "abcd"));
    
        // uses pair's template constructor
        m.emplace("d", "ddd");
    
        // uses pair's piecewise constructor
        m.emplace(std::piecewise_construct,
                  std::forward_as_tuple("c"),
                  std::forward_as_tuple(10, 'c'));
    
        for (const auto &p : m) {
            std::cout << p.first << " => " << p.second << '\n';
        }
    }