运行代码:
//list与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;
}//----------------------------------------------------------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.push_back(Item("horse shoe", 99, 12.34));ll.push_back(Item("Canon S400", 9988, 499.95));list<Item>::iterator p(ll.begin());while(p!=ll.end()){if (p->iid == 99 || p->iid == 9988){ll.erase(p);p = ll.begin();if(p!=ll.begin())p--;continue;}p++;}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
运行结果: