c++ - emplace 和 unordered_map<?, std::array<?, N>>

标签 c++ dictionary unordered-map stdarray emplace

我有一个 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/

相关文章:

C++:将自定义哈希键值从 unordered_map 输出到 std::cout 时出错

c++ - boost 如何避免 32 位机器上的 ABA 问题?

c# - 从 C++ 创建 COM 对象?

python - 字典似乎没有添加新键

python - 如何在字典中的现有键中添加新值(而不丢失以前的值)?

c++ - 如何在 C++ 中修改 unordered_map 中的每个值

c++ - C++ 标准不提供这种类型的散列

c++ - 删除在另一个函数中分配的内存?

java - 将 BouncyCaSTLe 签名转换为 Crypto++ 格式

python - 如何使用 Numba 加速 python 的字典