我尝试按原样实现您的代码。它似乎按降序对向量进行排序。尝试从 myfunc 函数切换真假。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool myfunc(vector<long> vec1,vector<long> vec2){
int i=0;
while(i<vec1.size()){
if(vec1[i]<vec2[i]){
return false;
}
else if(vec1[i]>vec2[i]){
return true;
}
i++;
}
return false;
}
int main()
{
int N = 5, M = 5;
vector< vector<long> > Data(N,vector<long>(M));
for ( int i = 0; i < Data.size(); i++ ) {
for ( int j = 0; j < Data[i].size(); j++ )
Data[i][j] = 5-i;
}
sort( Data.begin(), Data.end(), myfunc );
for ( int i = 0; i < Data.size(); i++ ) {
for ( int j = 0; j < Data[i].size(); j++ )
cout << Data[i][j] << " " ;
cout << endl;
}
return 0;
}
输出:
5 5 5 5 5
4 4 4 4 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
在切换真假之后,以下代码以正确的顺序对向量进行排序。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool myfunc(const vector<long> &vec1, const vector<long> &vec2){
int i=0;
while(i<vec1.size()){
if(vec1[i]<vec2[i]){
return true;
}
else if(vec1[i]>vec2[i]){
return false;
}
i++;
}
return true;
}
int main()
{
int N = 5, M = 5;
vector< vector<long> > Data(N,vector<long>(M));
for ( int i = 0; i < Data.size(); i++ ) {
for ( int j = 0; j < Data[i].size(); j++ )
Data[i][j] = 5-i;
}
sort( Data.begin(), Data.end(), myfunc );
for ( int i = 0; i < Data.size(); i++ ) {
for ( int j = 0; j < Data[i].size(); j++ )
cout << Data[i][j] << " " ;
cout << endl;
}
return 0;
}
输出
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5