Hobbyist
Hobbyist

Reputation: 925

What is the correct way to instantiate std::map<>

Class Base {
public:
    std::map<std::string, std::string> animals;
};

Which of the following is the correct way of instantiating a std::map<>?

Derived::Derived() {
    animals["Rabbit"] = "Killer Rabbit";
    //or
    animals.insert( std::pair<std::string,std::string>("Rabbit","Killer Rabbit") );
}

Upvotes: 1

Views: 4363

Answers (3)

Kupto
Kupto

Reputation: 2992

The answer depends on what you expect to happen...

the animals.insert(std::make_pair("Rabbit", "Killer Rabbit")); will fail if the key "rabbit" is already in use. See this.

the animals["Rabbit"] = "Killer Rabbit"; method will always change the animals["Rabbit"] element. Have a look at the operator[] reference.

The prior method has an advantage. It is that you can specify where to start looking for the key value. This could be potentially time-saving.

Upvotes: 1

Andy Prowl
Andy Prowl

Reputation: 126432

Inside a function, you should do either this:

animals["Rabbit"] = "Killer Rabbit";

Or this:

animals.insert(std::make_pair("Rabbit", "Killer Rabbit"));

In C++11, the latter form above can be shortened to:

animals.insert({"Rabbit", "Killer Rabbit"});

C++11 also offers a further possibility, which will construct the pair in-place:

m.emplace("test1", "t2");

As shakurov correctly mentions in the comment, the main difference between the first form and the remaining ones is that the first form will overwrite the value associated to the "Rabbit" key if that is present already, while the other forms will not.

Also, as pointed out by Dave S - again in the comments - the first form default-constructs the value and later assigns it, which is not the case for the other three forms.

Upvotes: 6

qPCR4vir
qPCR4vir

Reputation: 3571

Class Derived {
Public:
    Derived(){ animals["Rabbit"] = "Killer Rabbit";}

Will work. The second variant could be a litter more efficient is correctly used. The difference is that here you insert a pair "Rabbit","" with than is modified to "Rabbit","Killer Rabbit", while the second insert direct the final value.

Upvotes: 0

Related Questions