如果我想通过它所拥有的两种变量之一对UDT的向量进行排序,标准库排序是否可以执行此操作,或者我是否需要编写自己的排序函数.
例如,如果你有
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
Run Code Online (Sandbox Code Playgroud)
那么这可能使用stdlib排序吗?谢谢.
Ale*_*x B 11
如果类型实现"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) { }
};
Run Code Online (Sandbox Code Playgroud)
或者,您可以将排序函数(或函子)作为第三个参数传递给sort()而不是实现运算符"<".
bool type_is_less(const MyType& t1, const MyType& t2) { ... }
...
std::sort(c.begin(), c.end(), type_is_less);
Run Code Online (Sandbox Code Playgroud)
这在以下情况下很有用:
"<"因为某种原因实现运营商,| 归档时间: |
|
| 查看次数: |
3821 次 |
| 最近记录: |