MrN*_*man 5 c++ sorting projection comparator
我为此搜索了 c++ 模拟(python):
sorted(vector, key=lambda x : my_function(x))
Run Code Online (Sandbox Code Playgroud)
当然还有构造:
std::sort(vector.begin(), vector.end(), [](const auto& lhs, const auto& rhs) {
return my_function(lhs) < my_function(rhs);
});
Run Code Online (Sandbox Code Playgroud)
我只是想知道是否存在单参数构造。
如果我正确理解了这个问题,那么您是在问标准库中是否有一个排序函数,可以按给定的键而不是使用比较器进行排序。
标准库中没有类似的东西。在Python中,由于对象是基于表的——因为结构或记录的基本概念最终在语言中实现为字符串键和可能是函数的值之间的映射——所以可以简洁地引用字段作为字符串。在 C++ 中,情况并非如此。如果你有类似的东西
struct Foo {
std::string name;
int id;
};
Run Code Online (Sandbox Code Playgroud)
正在运行的程序不知道字段的名称“name”和“id”;它们仅作为源代码的工件而存在。因此,要执行类似 Python 基于键的排序之类的操作,您需要提供一个函数(或无论如何可调用对象)来从每个项目中提取要使用的键值。
像下面这样的东西会起作用:
template<typename Iter, typename Func>
void sort_by_key(Iter from, Iter to, Func get_key) {
std::sort(from, to,
[get_key](auto lhs, auto rhs) {
return get_key(lhs) < get_key(rhs);
}
);
}
struct Foo {
std::string name;
int id;
};
...
std::vector<Foo> foobar{ {"quux", 10000}, {"mumble", 12}, {"frobnicate", 42} };
sort_by_key(foobar.begin(), foobar.end(), [](const Foo& foo) {return foo.name; });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
695 次 |
| 最近记录: |