emplace and unordered_map<?, std::array<?, N>>

emplace and unordered_map<?, std::array<?, N>>

本文关键字:gt lt array map std unordered and emplace      更新时间:2023-10-16

我有一个std::unordered_map<string, std::array<int, 2>>emplace将值输入到映射中的语法是什么?

unordered_map<string, array<int, 2>> contig_sizes;
string key{"key"};
array<int, 2> value{1, 2};
// OK ---1
contig_sizes.emplace(key, value);
// OK --- 2
contig_sizes.emplace(key, std::array<int, 2>{1, 2});
// compile error --3
//contig_sizes.emplace(key, {{1,2}});
// OK --4 (Nathan Oliver)
// Very inefficient results in two!!! extra copy c'tor
contig_sizes.insert({key, {1,2}});
// OK --5
// One extra move c'tor followed by one extra copy c'tor
contig_sizes.insert({key, std::array<int, 2>{1,2}});
// OK --6 
// Two extra move constructors
contig_sizes.insert(pair<const string, array<int, 2>>{key, array<int, 2>{1, 2}});

我正在使用clang++ -c -x c++ -std=c++14和clang 3.6.0

我在中测试了代码http://ideone.com/pp72yR

附录:(4( 由Nathan Oliver在下方的答案中提出

来自cppreference std::unordered_map::emplace被声明为

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

因此,它试图推导传递给它的类型

--一种函数参数,其相关参数为初始值设定项列表(8.5.4(,但该参数没有指定从初始值设定值列表中推导的类型(14.8.1.1(。[示例:

template<class T> void g(T);  
g({1,2,3}); // error: no argument deduced for T

--结束示例]

因此,没有任何类型能够被推导出来。

如果你想在飞行中创建对象,那么你可以使用以下形式:

contig_sizes.emplace(key, std::array<int, 2>{1, 2});

或者我们可以创建一个typedef

typedef pair<const string, array<my_class, 2>> pair_type;

然后我们可以有

contig_sizes.emplace(pair_type{key, {1, 2}});

您也可以使用std::unordered_map::insert,它接受键/值的pair,该键/值可以从支撑的初始值设定项列表中构造。

contig_sizes.insert({key, {1, 2}});