c++ - 使用涉及地图的比较器对项目向量进行排序
问题描述
我有一个用例,我将向量中的所有元素映射到映射(哈希表)中的值。我现在想使用存储在地图中的这些值对向量进行排序。
static map<string, string> canonForm;
static bool myfunction(string a, string b){
return (canonForm[a] < canonForm[b]);
}
编辑:例如,在这里,canonForm 将为我的向量中的每个字符串(键)保存字符串(值)。上面的代码片段包含一个我想用作比较器来对字符串向量进行排序的函数。我将如何实施呢?上面的代码片段在编译过程中会弹出一个错误。
请让我知道我是否可以进一步改进问题
解决方案
这是一个如何执行此操作的示例。请参阅内联注释:
#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);
}
推荐阅读
- r - Foreach 循环在用户定义的函数中不起作用
- eslintrc - eslintrc.js/rules 中的 eslint 不起作用
- elasticsearch - 基于父嵌套字段对文档进行排序,无需无痛脚本
- mongodb - 执行聚合以在 pymongo 中按组查找平均值时的编码问题
- javascript - 可以将 HOF 与具有自动绑定的类功能一起使用吗?
- firebase - 类型“UploadMappingFileTask”属性“googleServicesResourceRoot”没有配置值
- swift - 如何在 Swift XCTest 单元测试中捕获标准输出和标准错误?
- g++ - dyld:库未加载:/usr/local/opt/icu4c/lib/libicuuc.68.dylib 原因:找不到图像
- reactjs - 如何实现 FlatList 项目计数器
- python-3.x - 如何在 praw 上获取主页提交