标准库排序和用户定义类型

tri*_*ker 4 c++

如果我想通过它所拥有的两种变量之一对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)

这在以下情况下很有用:

  1. 你不想"<"因为某种原因实现运营商,
  2. 你需要对一个内置或指针类型的容器进行排序,你不能重载运算符.
  3. 您希望使用不同的顺序对序列进行排序.例如:有时你想要一个带名字/名字的成员按名字排序的结构,其他时间按姓氏排序.两个不同的函数(或仿函数)使这些选项变得微不足道.