list与流迭代器stream_iterator

运行代码:

cpp 复制代码
//list与流迭代器
#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);
	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

运行结果:

相关推荐
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
weilx12344 天前
C++笔记-文件IO-<fcntl.h>
c++
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼4 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
Smileyqp沛沛4 天前
前端?C++ ?较大差异基础罗列
c++·基础·前端转c++
m0_547486664 天前
《数据结构教程》全套 PPT课件2026
数据结构
C语言小火车4 天前
C/C++ 为什么需要编译器?
开发语言·c++
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark4 天前
大规模并行计算中的负载均衡算法研究4
算法
吞下星星的少年·-·4 天前
C++ 萌新语法入门篇
c++·算法比赛