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

标签 c++

如果我想根据它持有的两种类型的变量之一对 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);

这在以下情况下很有用:

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

关于c++ - 标准库排序和用户定义类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1181246/

相关文章:

c++ - 访问与命令行参数关联的整数列表

c++ - 是否在空 std::forward_list 中定义了 before_begin() 之后的删除元素?

c++ - 用 XYZ + 旋转计算角度,我的敌人用他的 XYZ + 旋转计算角度 [线性代数]

c++ - 调用Referenced Vector的成员函数(size)抛出错误

c++ - 如何显示常量字符指针的地址

c++ - 如何在模板参数中使用 std::is_pod?

c++ - 这是什么意思?这是关于c++中的DWORD变量

c++ - 使用 C++ 可视化 FF 装箱

c++ - 如何使用 Git 子模块和 CMake 处理传递依赖冲突?

c++ - 为什么我不能 range-for 遍历任意内容的初始化列表?