简体   繁体   English

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

[英]Sort a vector of items with a comparator involving a map

I have a use case in which I map all my elements in a vector to values in a map (Hash Table). 我有一个用例,其中我将向量中的所有元素都映射到映射(哈希表)中的值。 I now want to sort the vector using these values stored in the map. 我现在想使用存储在地图中的这些值对向量进行排序。

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

EDIT: For example, here, canonForm will hold strings (value) for each string (key) in my vector. 编辑:例如,在这里,canonForm将为我的向量中的每个字符串(键)保存字符串(值)。 The snippet above contains a function I want to use as a comparator to sort the vector of strings. 上面的代码段包含一个函数,我想将其用作比较器以对字符串向量进行排序。 How would I go about implementing this? 我将如何实施呢? The above snippet pops an error during compilation. 上面的代码片段在编译过程中弹出错误。

Please let me know if I can improve the question further 请让我知道是否可以进一步改善问题

Here is an example of how to do this. 这是如何执行此操作的示例。 See the notes inline: 参见内联注释:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM