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

C++ 标准库排序和用户定义类型,c++,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 s

如果我想用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
struct MyType{
INTA;
int b;
};
向量moo;
//做一些将数据推回到moo的事情
排序(moo.begin(),moo.end())//但对a按从低到高排序,而不是b

那么,使用stdlib排序可以实现这一点吗?谢谢。

如果您的类型实现了
“bool运算符<(…)const”
和一个复制构造函数(编译器生成或自定义),则可以使用标准函数

这在以下情况下非常有用:


  • 您不想实现运算符
    “有三种方法:


    您可以重载
    运算符或另一个选项是为您的类型专门化
    std::less
    。这样您就不必每次都传递函子(例如,因为确实有一个合理的定义),而且您的类型没有得到
    运算符type\u is\u less也可以是“函数对象”(重载()运算符的对象)这在
    operator@sbi:typo.operator<应该是上面一段中指定的常量。@Checkers:好的,我删除了我的否决票。:)不过,我强烈希望实现所有二进制运算符,将两个操作数都视为相同的(即不更改它们)作为自由函数。对于成员函数,左手操作数可能会被视为不同的操作数。对于类似比较的运算符,您永远不会希望这样。
    
    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) { }
    };
    
    bool type_is_less(const MyType& t1, const MyType& t2) { ... }
    ...
    std::sort(c.begin(), c.end(), type_is_less);
    
    bool operator<(const MyType& lhs, const MyType& rhs) {return lhs.a<rhs.a;}
    
    struct compare_by_a {
      bool operator()(const MyType& lhs, const MyType& rhs) const
      {return lhs.a<rhs.a;}
    };