【发布时间】:2015-10-06 14:08:33
【问题描述】:
我有一个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 在下面的答案中提出
【问题讨论】:
-
emplace需要推断其参数的类型,但{{1,2}}没有类型(它不是表达式)。
标签: c++ dictionary unordered-map stdarray emplace