c++ - 如何在 C++ 中使用对索引加速映射?

标签 c++ dictionary unordered-map std-pair

我有一张以 pair 为索引的 map 。我发现访问其中的元素需要花费很多时间。我想知道是否有一些方法可以加速这个过程?我的代码如下:

std::vector words;
...to generate a words vector...
std::map<std::pair<std::string, std::string>, int> wordCountMap;
wordsSize = words.size()
for(int i = 0; i < wordsSize; ++i){
    for(int j = i + 1; j < min(i + e, wordsSize); ++j){
        std::pair<std::string, std::string> pk = words[i] < words[j] ? std::make_pair(words[i], words[j]) : std::make_pair(words[j], words[i]);
        wordPairCountMap[pk] = wordPairCountMap.find(pk) != wordPairCountMap.end() ? wordPairCountMap[pk] + 1 : 1;
    }
}

我发现pair indexed map的构建花费了很多时间。我该如何优化它?

最佳答案

++wordPairCountMap[pk];

可以代替

wordPairCountMap[pk] = wordPairCountMap.find(pk) != wordPairCountMap.end() ?
                           wordPairCountMap[pk] + 1 : 1;

避免额外的查找。

另请注意,您使用配对做了很多字符串复制

关于c++ - 如何在 C++ 中使用对索引加速映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40101861/

相关文章:

c++ - 使用 boost::program_options 解析 LPTSTR* 命令行参数

C++ 和 SDL 井字游戏 - 改变轮流

dictionary - map 与 mapM 行为

C++ 无序映射

c++ - 与 ‘operator<<’ 不匹配(操作数类型为 ‘std::ostream’ {aka ‘std::basic_ostream<char>’ } 和 ‘const std::type_index’ )

c++ - 不识别键盘输入

C++ 地址簿

android - 如何将 Android 二进制字典解码为人类可读的格式,如 .xml

java - 在五仙词典中添加新术语

c++ - unordered_map 无法检索在参数中指定为变量的键的值