[英]emplace and unordered_map<?, std::array<?, N>>
我有一個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中測試了代碼
附錄:Nathan Oliver在以下答案中建議了(4)
從cppreference std::unordered_map::emplace
聲明為
template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );
因此,它試圖推斷傳遞給它的類型。 這發揮了作用[temp.deduct.type]§14.8.2.5
—與關聯參數為初始值設定項列表(8.5.4)的函數參數,但該參數不具有為其指定初始值設定項列表的推導的類型(14.8.2.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}});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.