按照结构体中的2个关键变量排序。
typedef struct __tree_node
{
int no;
double height;
int age;
int level;
char name[12];
char addr[64];
} tree_node;
需要排序一组这样的结构体,从大到小,age最大的在最前面,如果age相同就按照height来从大到小排序。
有现成的算法来排序么?
[解决办法]
自己写一个比较大小的函数吧
int less(const tree_node *p1, const tree_node *p2){ if (p1->age < p2-> age) { return 1; } if (p1->age == p2->age && p1->height < p2->height) { return 1; } return 0;}
[解决办法]
重载一下比较大小的< > = 的运算符
然后用 C++标准库里提供的sort
例子如下:
// sort algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
vector<int>::iterator it;
// using default comparison (operator <):
sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
[解决办法]
#include<iostream>#include<vector>#include<algorithm>using namespace std;typedef struct __tree_node{ int no; double height; int age; int level; char name[12]; char addr[64];} tree_node;inline bool operator > (const tree_node& n1,const tree_node& n2) { if(&n1 != &n2) { if(n1.age > n2.age) { return true; } else if(n1.age == n2.age ) { if(n1.height > n2.height) return true; else return false; } else { return false; } } return false;}inline bool operator < (const tree_node& n1, const tree_node& n2) { return !(n1 > n2);}bool mysort(const tree_node& n1,const tree_node& n2) { return n1 > n2;}int main(void) { vector<tree_node> v; tree_node n1 = {1,3.4,8,3,"abc","dd"}; tree_node n2 = {1,3.4,28,3,"abc","ee"}; v.push_back(n1); v.push_back(n2); for(vector<tree_node>::iterator it = v.begin(); it != v.end(); it++) { cout<<"age is "<<it->age<<"\t height is "<<it->height<<endl; } sort(v.begin(),v.end(),mysort); for(vector<tree_node>::iterator it = v.begin(); it != v.end(); it++) { cout<<"age is "<<it->age<<"\t height is "<<it->height<<endl; } return 0;}