我已经重载了少于操作pair<int,int>,因此我可以以特定方式对矢量进行排序.我希望它按照一对中的第一个键按升序排列,如果第一个键相等,那么根据第二个键,我希望它按降序排列.
问题是sort函数似乎没有使用重载<运算符,但如果<在2对上调用,则返回的输出是我所期望的.我附上了一段代码,我用它来测试:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool operator<(pair<int, int> &a, pair<int, int> &b)
{
if (a.first < b.first) return true;
else if ((a.first == b.first) && (a.second > b.second)) return true;
return false;
}
int main() {
vector<pair<int, int>> test {make_pair(1,10), make_pair(3,4), make_pair(3,8), make_pair(6, 23), make_pair(1,6)};
sort(test.begin(), test.end());
for (int i = 0; i < test.size(); i++)
cout << test[i].first << " - " << test[i].second << " ";
cout << endl;
auto a = make_pair(3,4);
auto b = make_pair(3,8);
cout << (a < b) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输入向量是{(1,10), (3,4), (3,8), (6,23), (1,6)}.
我期待输出{(1,10), (1,6), (3,8), (3,4), (6,23)}.
获得的输出是{(1,6), (1,10), (3,4), (3,8), (6, 23)}.
如您所见,获得的输出是您使用标准<运算符而不会重载的结果.所以我认为这可能是一个问题,并检查(3,4) < (3,8).在这种情况下,根据我的重载运算符,答案返回false.那我哪里错了?为什么sort不受重载运算符的影响?有关类似问题的SO有各种各样的问题,但找不到任何帮助.
Ker*_* SB 11
operator<在std命名空间中已经定义了对,并且这std::sort是您正在使用的版本找到的对.从未发现过载.改为使用命名谓词:
struct MyPairComparator
{
bool operator()(const std::pair<int, int> & a,
const std::pair<int, int> & b) const
{
// ...
}
};
sort(test.begin(), test.end(), MyPairComparator()); // ADL, maybe
// ^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
此外,谓词应该可以使用常量值调用,因此可以通过值或const引用获取参数.
请注意,它sort位于std命名空间中.相比之下,当您使用<表达式时main,确实找到了您自己在全局命名空间中的重载.