istream_iterators
ostream_iterators
区别1:
*in返回的是一个右值,即我们无法通过istream_iterators对输入流本身进行修改
out返回的是一个左值,即我们可以写入到ostream中去
区别2:
In的++ operator是有意义的,我们可以通过++,对流进行枚举:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <iterator>
using namespace std;
int main()
{
string filename("2.txt");
fstream fs(filename, std::ios::in);
if (!fs.is_open()) {
std::cout << "Failed to open the file." << std::endl;
return 1;
}
istream_iterator<int> in1(fs),eof;
cout << "output the file content" << endl;
for (istream_iterator<int> beg1=in1; beg1 != eof; beg1++)
{
cout <<* beg1 << endl;
}
fs.close();
}
out的*和++定义成了,不会做任何操作,即在我们每次使用out对输出流进行操作的时候, out会自动实现自加的操作,可以想象是因为,插入了一个元素,out的位置自动向后移动,例如:
vector<int> sample{ 1,2,3,4,5 };
ostream_iterator<int> ou(cout, " ");
cout << "output the vector sample via ou: " << endl;
for (auto& element : sample)
{
*ou++ = element;
}
它的效果和下面这段是一样的:
for (auto& element : sample)
{
ou = element;
}
输出: