运行代码:
//list与sort()
#include"std_lib_facilities.h"
//声明Item类
struct Item
{string name;int iid;double value;Item():name(" "),iid(0),value(0.0){}Item(string ss,int ii,double vv):name(ss),iid(ii),value(vv){}friend istream& operator>>(istream& is, Item& ii);friend ostream& operator<<(ostream& os, const Item& ii);};//------------------------------------------------------------
//重载Item类的输入和输出操作符
istream& operator>>(istream& is, Item& ii)
{is >> ii.name >> ii.iid >> ii.value;return is;
}ostream& operator<<(ostream& os, const Item& ii)
{os << ii.name << " " << ii.iid << " " << ii.value;return os;
}//----------------------------------------------------------
//定义根据name进行排序的函数(字典序)
bool sort_by_name(Item& ii1,Item& ii2)
{return ii1.name < ii2.name;
}//------------------------------------------------------------
//定义根据iid进行排序的函数(升序)
bool sort_by_iid(Item& ii1, Item& ii2)
{return ii1.iid < ii2.iid;
}//------------------------------------------------------------
//定义根据value进行排序的函数(降序)
bool sort_by_value(Item& ii1, Item& ii2)
{return ii1.value > ii2.value;
}//-------------------------------------------------------------
int main()
try
{cout << "输入读取文件名: ";string from_file;cin >> from_file;ifstream is(from_file.c_str());if (!is)error("can't open ", from_file);istream_iterator<Item>ii(is);istream_iterator<Item>eos;ostream_iterator<Item>oo(cout, "\n");list<Item>ll(ii, eos);ll.sort(sort_by_value);copy(ll.begin(), ll.end(), oo);return 0;
}
catch (exception& e) {cerr << "error:" << e.what() << '\n';keep_window_open();return 1;
}
catch (...) {cerr << "Oops:unknown exception!\n";keep_window_open();return 2;
}
读取文件:Item_file.txt
Max 2 43.2
Jane 3 34.2
Tom 3 32.4
Mary 8 23.0
Peter 5 32.5
Max 2 43.2
Jane 3 34.2
Tom 3 32.4
Mary 8 23.0
Peter 5 32.5
运行结果: