unordered_map::insert 将键值对复制或移动到容器中。 It is overloaded to accept reference-to-const or an rvalue reference:
std::pair<iterator,bool> insert(const std::pair<const Key, T>& value);
template<class P>
std::pair<iterator,bool> insert(P&& value);
unordered_map::emplace 允许您通过在适当位置构造元素来避免不必要的复制或移动。它使用完美转发和可变参数模板到forward arguments to the constructor of the key-value pair:
template<class... Args>
std::pair<iterator,bool> emplace(Args&&... args);
但是这两个功能之间有很多重叠之处。 emplace 可用于转发到键值对的复制/移动构造函数,这允许它像 insert 一样使用。这意味着使用emplace 并不能保证您会避免复制或移动。此外,采用右值引用的 insert 版本实际上是模板化的,并接受任何类型的 P,因此键值对可以从 P 构造。
Scott Meyers says:
原则上,进位功能有时应该更有效
比他们的插入同行,他们永远不应该少
高效。
(编辑: Howard Hinnant 运行 some experiments 显示有时 insert 比 emplace 快)
如果您确实想复制/移动到容器中,使用insert 可能是明智之举,因为如果您传递不正确的参数,则更有可能出现编译错误。您需要更加小心,您将正确的参数传递给 emplacement 函数。
unordered_map::emplace 的大多数实现将导致为新对动态分配内存,即使映射已经包含具有该键的项目并且emplace 将失败。这意味着如果emplace 很有可能会失败,您可能会使用插入获得更好的性能,以避免不必要的动态内存分配。
小例子:
#include <unordered_map>
#include <iostream>
int main() {
auto employee1 = std::pair<int, std::string>{1, "John Smith"};
auto employees = std::unordered_map<int, std::string>{};
employees.insert(employee1); // copy insertion
employees.insert(std::make_pair(2, "Mary Jones")); // move insertion
employees.emplace(3, "James Brown"); // construct in-place
for (const auto& employee : employees)
std::cout << employee.first << ": " << employee.second << "\n";
}
Edit2:应要求提供。还可以将unordered_map::emplace 与一个采用多个构造函数参数的键或值一起使用。使用std::pairpiecewise constructor,您仍然可以避免不必要的复制或移动。
#include <unordered_map>
#include <iostream>
struct Employee {
std::string firstname;
std::string lastname;
Employee(const std::string& firstname, const std::string& lastname)
: firstname(firstname), lastname(lastname){}
};
int main() {
auto employees = std::unordered_map<int, Employee>{};
auto employee1 = std::pair<int, Employee>{1, Employee{"John", "Smith"}};
employees.insert(employee1); // copy insertion
employees.insert(std::make_pair(2, Employee{"Mary", "Jones"})); // move insertion
employees.emplace(3, Employee("Sam", "Thomas")); // emplace with pre-constructed Employee
employees.emplace(std::piecewise_construct,
std::forward_as_tuple(4),
std::forward_as_tuple("James", "Brown")); // construct in-place
}