【问题标题】:Sort a vector of items with a comparator involving a map使用涉及地图的比较器对项目向量进行排序
【发布时间】:2018-10-08 13:58:25
【问题描述】:

我有一个用例,我将向量中的所有元素映射到映射(哈希表)中的值。我现在想使用存储在地图中的这些值对向量进行排序。

static map<string, string> canonForm;
static bool myfunction(string a, string b){
    return (canonForm[a] < canonForm[b]);
}

编辑:例如,在这里,canonForm 将为我的向量中的每个字符串(键)保存字符串(值)。上面的 sn-p 包含一个我想用作比较器来对字符串向量进行排序的函数。 我将如何实施呢?上面的sn -p在编译的时候会弹出一个错误。

如果我可以进一步改进问题,请告诉我

【问题讨论】:

  • 问题是什么?您应该可以在向量上调用sort 并将其传递给myfunction
  • 还要注意std::map是一个二叉搜索树,没有哈希映射(如果你需要不断查找,你应该检查std::unordered_map

标签: c++ vector hashmap


【解决方案1】:

以下是如何执行此操作的示例。请参阅内联注释:

#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>

// Note #1 - consider using an unordered_map here for better performance
static std::unordered_map<std::string, std::string> canonForm;

static bool myfunction(std::string const& a, std::string const& b)
{
    // Note #2 - use the `at` member-function - it works on const maps and does not create a new entry if the key is not found
    return canonForm.at(a) < canonForm.at(b);
}


void sort_by_canonform(std::vector<std::string>& keys)
{
    // Note #3 - simply supply myfunction as the comparison function
    std::sort(std::begin(keys), std::end(keys), myfunction);
}

【讨论】:

  • 嗨,理查德,感谢您的及时回答和详细的 cmets。我会尽快尝试你的建议
猜你喜欢
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 2020-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多