2016-12-02 3 views
0

私はソートされたデータを読み取り、次のように挿入していますマップのマップのマップを持っている:emplaceをヒントとマップマップで使用する方法は?

データ:

a,a,a,a 
a,a,a,b 
a,a,a,c 
... 
z,z,z,z 

のような挿入は、次のとおりです。

std::map<string,std::map<string,std::map<string,string>>> theMap; 
// For each line: 
theMap[v1][v2][v3]=v4 

はする方法はあります上記の操作を行いますが、v要素ごとにemplaceとヒントを使用しますか?私はデータがソートされているのでヒントを使いたい。

答えて

1

必要なメンバー関数はemplace_hintで、ヒントイテレータを最初のパラメータとして使用します。新しく挿入されたアイテムのイテレータを返すので、それを増分して次のemplaceのヒントとして使用できます。

1

は、ここでは一例

#include <map> 
#include <string> 

template <typename Key, typename Val> 
Val& sorted_insert(std::map<Key,Val>& map, const Key& key, const Val& val) { 
    auto it = map.emplace_hint(map.end(),key, val); 
    return it->second; 
} 

/// avoids calling default constructor unless necessary, which could do expensive allocations/deallocations 
template <typename Key, typename Val> 
Val& sorted_insert_default(std::map<Key,Val>& map, const Key& key) { 
    auto it = map.emplace_hint(map.end(),std::piecewise_construct_t(), std::tie(key), std::make_tuple()); 
    return it->second; 
} 
using map_t = std::map<std::string,std::map<std::string,std::map<std::string,std::string>>>; 
void add_row(map_t& map, const std::string&v1, const std::string& v2, const std::string& v3, const std::string&v4) { 
    sorted_insert(sorted_insert_default(sorted_insert_default(map,v1),v2),v3,v4); 
} 
です
関連する問題