使用包含地图的比较器对项目向量进行排序

时间:2018-10-08 13:58:26

标签: c++ vector hashmap

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

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

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

请让我知道我是否可以进一步改善问题

1 个答案:

答案 0 :(得分:0)

这是如何执行此操作的示例。参见内联注释:

#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);
}
相关问题