我有一个 std::unordered_map<string, std::array<int, 2>>
. emplace
的语法是什么?正在向 map 中输入值?
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 );
因此它会尝试推断传递给它的类型。这会发挥作用 [temp.deduct.type] § 14.8.2.5
— A function parameter for which the associated argument is an initializer list (8.5.4) but the parameter does not have a type for which deduction from an initializer list is specified (14.8.2.1). [ Example:
template<class T> void g(T); g({1,2,3}); // error: no argument deduced for T
—end example ]
因此无法推导出任何类型。
如果您想动态创建对象,那么您可以使用以下形式:
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
它采用一对 键/值,可以从花括号初始化列表构造。
contig_sizes.insert({key, {1, 2}});
关于c++ - emplace 和 unordered_map<?, std::array<?, N>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32972132/