2016-12-02 79 views
0

我有地圖地圖可以看到我在看書排序的數據和插入的地圖如下:如何使用地圖提示和地圖地圖?

數據:

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); 
}