按照结构体数组的某一项排序,那么一个结构体包含的元素仍保持不变
结果如下:
代码:
1 #include<algorithm> 2 #include<iostream> 3 using namespace std; 4 5 const int M = 3; 6 7 struct two { 8 double w; 9 double v; 10 }ss[M]; 11 bool cmp(two a,two b) 12 { 13 return a.v > b.v; //按照从大到小排序 14 } 15 16 int main() 17 { 18 int s, e; 19 cout << "输入结构体数组的数值,以空格分开: " << endl; 20 for (int i = 0; i < 3; ++i) 21 { 22 cin >> s >> e; 23 ss[i].w = s; 24 ss[i].v = e; 25 //cout << ss[i].w << " " << ss[i].v << endl; 26 } 27 sort(ss, ss + 2, cmp); 28 29 cout << "排序后如下:" << endl; 30 for (int i = 0; i < 3; ++i) 31 { 32 cout << ss[i].w << " " << ss[i].v << endl; 33 } 34 35 cin.ignore(); 36 cin.ignore(); 37 cin.ignore(); 38 39 40 return 0; 41 }
时间: 2024-10-08 14:49:58