The emplace()
method constructs the key-value pair directly within the map, while insert()
requires creating the pair outside the map and then moving or copying it in.
Using emplace()
can be more efficient, especially when the key or value type is expensive to copy or move. Here's an example:
#include <iostream>
#include <string>
#include <unordered_map>
struct User {
std::string Name;
// Other data members...
User(const std::string& name) : Name{name} {
std::cout << "User constructed\n";
}
};
int main() {
std::unordered_map<std::string, User> users;
users.emplace("john", "John");
auto [it, success] = users.insert(
{"alice", User{"Alice"}}
);
}
User constructed
User constructed
When using emplace()
, the User
object is constructed directly within the map using the provided arguments. With insert()
, we first construct a User
object outside the map and then insert it, resulting in an extra construction.
However, if you already have an existing key-value pair object, using insert()
can be more convenient and readable.
In summary, prefer emplace()
when you have the individual key and value components available, especially for complex types. Use insert()
when you already have a key-value pair object ready to be inserted.
Answers to questions are automatically generated and may not have been reviewed.
std::unordered_map
Creating hash maps using the standard library's std::unordered_map
container