首页 > 解决方案 > 使用涉及地图的比较器对项目向量进行排序

问题描述

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

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

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

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

标签: c++vectorhashmap

解决方案


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

#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);
}

推荐阅读