今天帮一位同学用曹自强同学解决了http://student.csdn.net/space.php?uid=42616&do=thread&id=2837一文的反向输出序列内容问题,利用copy算法加流迭代器,只用了一行代码,特此总解了一下流迭代器的一些经典用法。用好了真的很强大,希望对有需要的同学有帮助
//利用流迭代器填充vector
{
ifstream in("test.txt");
istream_iterator<string> ibegin(in);
istream_iterator<string> iend;
vector<string> vec(ibegin, iend);
copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, "/n"));
}
//利用输入流填充vector
{
vector<string> vec;
copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(vec));
sort(vec.begin(), vec.end());
copy(vec.begin(), vec.end(), ostream_iterator<string>(cout,"/n"));
}
//利用流迭代器保存vector内容到文件
{
ifstream in("test.txt");
istream_iterator<string> ibegin(in);
istream_iterator<string> iend;
vector<string> vec(ibegin, iend);
ofstream out("testcopy.txt");
copy(vec.begin(), vec.end(), ostream_iterator<string>(out, "/n"));
}