排序有关问题 急
排序问题 急!
struct stu
{
int a1;
int a2;
int a3;
....
....
.....
int a59;
}
vector<stu> v;
v[0] = a0 a1 a2.....到a59
v[1] = a0 a1 a2.....到a59
.....
用a2作为索引怎么把vector从小到大排序。
------解决方案--------------------
struct stu
{
int a1;
int a2;
int a3;
....
....
.....
int a59;
}
vector<stu> v;
v[0] = a0 a1 a2.....到a59
v[1] = a0 a1 a2.....到a59
.....
用a2作为索引怎么把vector从小到大排序。
------解决方案--------------------
- C/C++ code
#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; }
------解决方案--------------------
重载个operator<
bool operator<(const Student& s1, const Student& s2)
{
if (s1.a2 < s2.a2)
return true;
else
return s1.a1 < s2.a1;
//根据需要自己改
}
std::sort(sutVector.begin(), stuVector.end());
------解决方案--------------------
我在 VC6.0上没错啊
- C/C++ code
#include<iostream> #include<algorithm> #include<vector> using namespace std; struct stu { int a1,a2,a3,a4; }; bool cmp(stu a, stu b) { if(a.a2 == b.a2) return a.a1 < b.a1; else return a.a2 < b.a2; } int main() { vector<stu> v; stu st1,st2,st3; st1.a1= 3; st1.a2=4;st1.a3=5;st1.a4=6; v.push_back(st1); st2.a1= 2; st2.a2=4;st2.a3=5;st2.a4=6; v.push_back(st2); st3.a1= 1; st3.a2=4;st3.a3=5;st3.a4=6; v.push_back(st3); sort(v.begin(), v.end(), cmp); for(int i = 0; i<3; ++i) { cout<<v[i].a1<<" "; } cout<<endl; return 0; }