c++ - 我的重载运算符 < 不适用于 cpp 中的排序函数

标签 c++ sorting operator-overloading

我想在 2 对之间重载运算符 <。当我使用 < 进行比较时它有效,但当我使用 built_in cpp 排序函数时它不起作用。 #包括 使用命名空间标准;

typedef pair<int,int> pii;

bool operator < (const pii &a,const pii &b){
    return a.second<b.second;
}

int main()
{
    pii a,b;
    a=make_pair(1,4);
    b=make_pair(2,3);
    if(a<b) cout<<"a<b\n";
    else cout<<"b<a\n";

    vector<pii> v;
    v.push_back(a);
    v.push_back(b);
    sort(v.begin(),v.end());

    for(auto x:v)
        cerr<<x.first<<" "<<x.second<<endl;

    return 0;
}

输出:

b<a
1 4
2 3

我很困惑为什么它不打印:

b<a
2 3
1 4

最佳答案

std::pair已经有一个内置的 operator< .如果您想按不同的标准排序,您可以传递一个比较函数。

std::sort(v.begin(),v.end(), [](auto& lhs, auto& rhs){ return lhs.second < rhs.second; });

关于c++ - 我的重载运算符 < 不适用于 cpp 中的排序函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55075790/

相关文章:

ios - 如何计算 parse.com 查询中数组值的数量?

c++ - 无法解释此 C++ 代码

c++ - 如何将 const WCHAR * 转换为 const char *

c++ - 非终止 while 循环

c++ - 广义排序函数和使用 binary_function

swift - 排序的解释(按 :) in Swift

c++ - 在 C++17 中重载命名空间和子命名空间中的运算符是不明确的

c++ - 在指针上重载 operator++

c++ - 如何读取 C++ 中的重音字符并将它们与 isalnum 一起使用?

c++ - 使用 Ceres 求解器进行 CMake-ing 项目时冲突的 Eigen 依赖项