运行代码:
//向量vector与erase()
#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");
vector<Item>vi(ii, eos);
vi.push_back(Item("horse shoe", 99, 12.34));
vi.push_back(Item("Canon S400", 9988, 499.95));
for (int i = 0; i < vi.size(); i++)
{
if (vi[i].name == "horse shoe" || vi[i].name == "Canon S400")
{
vi.erase(vi.begin() + i);
i--;
}
}
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
运行结果: