运行代码:
//向量与sort()
#include"std_lib_facilities.h"
//声明Item类
struct Item
{
string name;
int iid;
double value;
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");
vector<Item>vi(ii, eos);
sort(vi.begin(),vi.end(), sort_by_value);
copy(vi.begin(), vi.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
运行结果:文章来源:https://www.toymoban.com/news/detail-614388.html
文章来源地址https://www.toymoban.com/news/detail-614388.html
到了这里,关于向量vector与sort()的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!