LZ你可能理解错了。并不是任何定义了<<预算的类型都可以做为参数来初始化ostream_iterator(输出流迭代器)。应该是只有basic_ostream和继承了这个类的类才能当作参数来初始化ostream_iterator。可能因为以上类型基本都重载了<<,所以LZ才搞错了吧。
最常用的basic_ostream类型的变量其实就是cout
以下就是MSDN中的范例
// ostream_iterator_ostream_iterator.cpp
// compile with: /EHsc
#include <iterator>
#include <vector>
#include <iostream>
int main( )
{
using namespace std;
// ostream_iterator for stream cout
ostream_iterator<int> intOut ( cout , "\n" );
*intOut = 10;
intOut++;
*intOut = 20;
intOut++;
int i;
vector<int> vec;
for ( i = 1 ; i < 7 ; ++i )
{
vec.push_back ( i );
}
// Write elements to standard output stream
cout << "Elements output without delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( cout ) );
cout << endl;
// Write elements with delimiter " : " to output stream
cout << "Elements output with delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( cout, " : " ) );
cout << endl;
}
这是输出
10
20
Elements output without delimiter: 123456
Elements output with delimiter: 1 : 2 : 3 : 4 : 5 : 6 :
同样
任何一个ofstream或支持写的fstream类型也能当ostream_iterator的参数。
比如将上面的范例稍加修改:
// ostream_iterator_ostream_iterator.cpp
// compile with: /EHsc
#include <iterator>
#include <vector>
#include <fstream>
int main( )
{
using namespace std;
ofstream file("test.txt"); //用ofstream类型的file代替了cout
ostream_iterator<int> intOut ( file , "\n" );
*intOut = 10;
intOut++;
*intOut = 20;
intOut++;
int i;
vector<int> vec;
for ( i = 1 ; i < 7 ; ++i )
{
vec.push_back ( i );
}
// Write elements to standard output stream
file << "Elements output without delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( file ) );
file << endl;
// Write elements with delimiter " : " to output stream
file << "Elements output with delimiter: ";
copy ( vec.begin ( ), vec.end ( ),
ostream_iterator<int> ( file, " : " ) );
file << endl;
}
运行后会生成一个test.txt文件。内容为:
10
20
Elements output without delimiter: 123456
Elements output with delimiter: 1 : 2 : 3 : 4 : 5 : 6 :
温馨提示:答案为网友推荐,仅供参考