内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
有什么方法来设置std::pair
?
std::unordered_map<int, std::pair<std::string, std::string>> my_map; my_map.emplace(1, "foo", "bar"); // Error
当然可以插入:
my_map[2] = std::make_pair("bar", "foo");
但这不需要不必要的复制/移动吗?
如果您有一个std::map
映射到不能以这种方式有效构造的类型,C++11提供std::piecewise_construct
为std::pair
成为emplace
d.
struct A { }; // nothing struct C { C(C&&)=delete; }; // no copy/move struct B { B()=delete; B(B&&)=delete; B(C&&, C&&) {}; }; // no copy/move, only annoying ctor std::map< int, std::pair<A,B> > test; // test.emplace( 0, std::make_pair( A{}, B{} ); // does not compile // test.emplace( 0, std::make_pair( A{}, B{C{},C{}} ); // does not compile test.emplace( std::piecewise_construct, std::make_tuple(0), std::forward_as_tuple( std::piecewise_construct, std::forward_as_tuple(A{}), std::forward_as_tuple( C{}, C{} ) ) ); // compiles!