如果我想根据它持有的两种类型的变量之一对 UDT 的 vector 进行排序,标准库排序是否可以执行此操作,或者我是否需要编写自己的排序函数。
例如,如果你有
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 排序是否可行?谢谢。
最佳答案
如果您的类型实现了 "bool operator < (...) const"
,则可以使用标准函数和一个复制构造函数(编译器生成的或自定义的)。
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()
。而不是实现运算符 "<"
.
bool type_is_less(const MyType& t1, const MyType& t2) { ... }
...
std::sort(c.begin(), c.end(), type_is_less);
这在以下情况下很有用:
- 你不想实现运算符
"<"
无论出于何种原因, - 您需要对不能重载运算符的内置或指针类型的容器进行排序。
- 您希望使用不同 顺序对序列进行排序。例如:有时您需要一个结构,其名字/姓氏成员按名字排序,其他时候按姓氏排序。两个不同的函数(或仿函数)使这些选择变得微不足道。
关于c++ - 标准库排序和用户定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1181246/