结构列表,如何根据某个字段排序?
//请看代码
//环境vc 6.0
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
struct Test_Struct
{
long Item1;
long Item2;
};
struct item1_less_than{
bool operator()(const Test_Struct& _X, const Test_Struct& _Y) const
{return (_X.Item1 < _Y.Item1); }
};
int main(int, char**)
{
list<Test_Struct> lstTest;
Test_Struct t1 = {1,13};
Test_Struct t2 = {22,2};
Test_Struct t3 = {3,33};
Test_Struct t4 = {34,4};
lstTest.push_back(t1);
lstTest.push_back(t4);
lstTest.push_back(t2);
lstTest.push_back(t3);
list<Test_Struct>::iterator itr = lstTest.begin();
cout << "before sort" << endl;
for(; itr != lstTest.end(); itr++)
{
cout << "(" << itr->Item1 << "," << itr->Item2 << ")" << endl;
}
//根据Item1排序
//sort(lstTest.begin(), lstTest.end(), item1_less_than());
cout << "sort by item1" << endl;
for(; itr != lstTest.end(); itr++)
{
cout << "(" << itr->Item1 << "," << itr->Item2 << ")" << endl;
}
cout << endl;
return 0;
}
//但是好像不行,我如何是好?