我有一张 map 的 map ,我正在读取排序的数据并按如下方式插入:
数据:
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 和 hint 之外,还有其他办法吗?我想使用提示,因为数据已排序。
最佳答案
举个例子
#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);
}
关于c++ - 如何使用 emplace with hint 和 map of maps?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929458/