我想根据特定标准对成对 vector 中的成对进行排序,因此我使用名为 sortPair 的函数重载了一个排序函数,但我不知道应该传递给该函数的适当参数是什么。
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
using namespace std;
bool sortPair (pair < int , int > &x , pair < int , int > &y)
{
if ( x.second % 2 == 0 && y.second % 2 == 0 && x.first == y.first )
{
if ( x.second > y.second )
{
return y.second < x.second ;
}
else
{
return x.second < y.second ;
}
}
if ( x.second % 2 != 0 && y.second != 0 && x.first == y.first )
{
if( x.second > y.second )
{
return y.second < x.second ;
}
else
{
return x.second < y.second ;
}
}
if ( x.second % 2 == 0 && y.second != 0 && x.first == y.first )
{
return y.second < x.second ;
}
if ( x.second % 2 != 0 && y.second == 0 && x.first == y.first)
{
return x.second < y.second ;
}
}
int main()
{
int t = 1;
while ( t -- )
{
int n , m , x;
cin>> n >> m ;
vector < pair < int , int > > u ;
for ( int i=0 ; i<n ; i++)
{
u.push_back(make_pair(x%m,x));
}
for ( int i=0 ; i<n ; i++)
{
sort(u.begin(),u.end(),sortPair(u.at(i),u.at(i+1)));
}
cout<<endl;
cout<<n<<" "<<m<<endl;
for (auto& e : u)
{
cout << e.first << "\n";
}
}
return 0;
}
最佳答案
很难理解你想要实现什么,但是看看这个函数:
#include <algorithm>
#include <functional>
#include <array>
#include <iostream>
int main()
{
std::array<int, 10> s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
// sort using the default operator<
std::sort(s.begin(), s.end());
for (int a : s) {
std::cout << a << " ";
}
std::cout << '\n';
// sort using a standard library compare function object
std::sort(s.begin(), s.end(), std::greater<int>());
for (int a : s) {
std::cout << a << " ";
}
std::cout << '\n';
// sort using a custom function object
struct {
bool operator()(int a, int b)
{
return a < b;
}
} customLess;
std::sort(s.begin(), s.end(), customLess);
for (int a : s) {
std::cout << a << " ";
}
std::cout << '\n';
// sort using a lambda expression
std::sort(s.begin(), s.end(), [](int a, int b) {
return b < a;
});
for (int a : s) {
std::cout << a << " ";
}
std::cout << '\n';
}
以上是std::sort.
中自定义比较函数的基本用法
看起来不对:
sort(u.begin(),u.end(),sortPair(u.at(i),u.at(i+1)));
您不必手动传递这两个变量。用法应该是:
sort(u.begin(),u.end(),sortPair));
此外,您的比较函数中缺少 const&。
关于c++ - 在 C++ 中重载自定义排序比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32488613/