标准库排序和用户定义的类型 [英] Standard library sort and user defined types
问题描述
如果我想通过两种类型的变量之一对UDT的向量进行排序,标准库排序是否可以做到这一点,或者我需要编写自己的排序函数。
If I want to sort a vector of a UDT by one of two types of variables it holds, is it possible for the standard library sort to do this or do I need to write my own sort function.
例如,如果你有
struct MyType{
int a;
int b;
};
vector<MyType> moo;
// do stuff that pushes data back into moo
sort(moo.begin(), moo.end()) // but sort it by lowest to highest for a, not b
这是可能使用stdlib排序吗?谢谢。
So is this possible using the stdlib sort? Thanks.
推荐答案
如果你的类型实现bool operator< ...)const
和一个复制构造函数(编译器生成或自定义)。
It is possible to use standard function if your type implements "bool operator < (...) const"
and a copy constructor (compiler-generated or custom).
struct MyType {
int a;
int b;
bool operator < (const MyType& other) const {
... // a meaningful implementation for your type
}
// Copy constructor (unless it's a POD type).
MyType(const MyType &other)
: a(other.a), b(other.b) { }
// Some other form of construction apart from copy constructor.
MyType()
: a(0), b(0) { }
};
或者,您可以将排序函数(或函子)作为第三个参数传递给 sort()
而不是实现运算符<
。
Alternatively, you can pass an ordering function (or a functor) as a third argument to sort()
instead of implementing operator "<"
.
bool type_is_less(const MyType& t1, const MyType& t2) { ... }
...
std::sort(c.begin(), c.end(), type_is_less);
这在以下情况下很有用:
This is useful in the following situations:
- 您不想因任何原因实施运算符
需要对内置或指针类型的容器进行排序,而不能对运算符进行重载。
- 您希望使用不同顺序对序列进行排序。例如:有时你想要一个结构,第一/姓名成员按名字排序,其他时间按姓氏排序。两个不同的函数(或函子)使得这些选项不重要。
- you don't want to implement operator
"<"
for whatever reason, - you need to sort a container of built-in or pointer types for which you can't overload operators.
- you wish to sort the sequence using different orderings. ex: sometimes you want a struct with first/last name members sorted by first name, other times by last name. two different functions (or functors) make such options trivial.
这篇关于标准库排序和用户定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!