2016-12-02 78 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); 
}