c++ - 如何使用 emplace with hint 和 map of maps?

标签 c++

我有一张 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/

相关文章:

c++ - "constant"GtkLabel 的 gtk+ 信号

c++ - SetProcessDPIAware 似乎在 Windows 10 下不起作用

c++ - 如何在 C++ 中正确存储正则表达式匹配

C++11 动态线程池

c++ - C++ 的分层内存分配器库

java - 用于 Java、Cpp 和 C 的 cscope

c++ - 有没有办法使用 C++ 类型特征来检查类型是否是模板及其任何属性?

c++ - try_emplace 的惰性参数评估?

c++ - 动态二维字符串数组,其中第二维可以更改

c++ - 如何从dll中的异步函数返回值