Emplacing a std::pair
Emplacing a std::pair
是否有放置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::对?
参数需要适用于pair<int, pair<string,string>>
的构造函数,即映射的value_type
:
my_map.emplace(1, std::make_pair("foo", "bar"));
但这难道不需要不必要的复制/移动吗?
否;make_pair
生成一对指向字符串文字的指针,然后将其用于初始化(在emplace
的情况下)或分配给(在[]
的情况下的)映射中包含的字符串。
在这种情况下,放置"值类型"std::pair
的部分没有什么意义,因为std::string
既可以有效地从C字符串转换,也可以有效地移动到映射中。简单的m.emplace( 3, std::make_pair( "bob", "alice" ) )
和你99%的方式达到最佳效率。
但是,如果您有一个std::map
映射到无法以这种方式有效构建的类型,则C++11为std::pair
提供std::piecewise_construct
,使其成为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!
实例
这是一种极端的情况,因为高效移动对象要常见得多。
有:
my_map.emplace(1, std::make_pair("foo", "bar"));
使用C++17,您可以使用try_emplace
来实现这一点:
std::unordered_map<int, std::pair<std::string, std::string>> my_map;
my_map.try_emplace(1, "foo", "bar");
相关文章:
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- c++:在switch中使用std::pair的可能性
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- Hash for a std::pair, for use in an unordered_map
- 类模板的参数太少 "std::pair":在函数中将 std 对作为参数传递
- 如何使用 std::sort with pair and references
- 如何在给定范围内找到 std::set<pair<int、int> > 中的最大值?
- C++ vector<pair<int,int>> std::all_of() 函数问题(重定向到头文件)
- 接收std :: Pair作为参数并从支撑列表初始化中推论的模板函数
- 如何更新最近在 std::vector<pair<int, int>> 中输入的元素?
- std::pair中的template-template参数
- std::experimental::ostream_joiner and std::pair
- 如何将两个std :: vector结合到一个std :: vector与std :: pair
- 错误 C2678:二进制'==':找不到采用 'std::pair<const _Kty,_Ty>' 型左操作数的运算符
- C++错误处理-使用std::pair或std::tuple返回错误代码和函数返回的缺点
- C++ 如何打印此地图 std::map<int, pair<vector<pair<int, int>>, int>>
- 我会看到使用 std::map 而不是 vector<pair<string、string> > 的性能提升吗?
- 在 std::set 中插入对不一致(无法识别 <pair>.second)
- 将std::pair转换为具有任意数量元素的std::tuple
- 宏MOCK_METHOD传递了3个参数,但std::pair只接受了2个错误