ostream_iterator属于I/O流STL适配器,用于获取一个元素,同时保存在缓冲器中,可以供Cout输出。如果把cout看做成一个对象,那么在Cout对象当中存在一片用于数据存储的区域。ostream_iterator在STL中一般配合copy函数一起使用,如下代码;
ostream_iterator<int> output(cout, " "); //关联cout,设置分隔符 <br> copy(ivec.begin(), ivec.end(), output); //元素拷贝到ostream_iterator所指向的对象cout <br> cout; //显示cout的值 </int> |
ostream_iterator<template>中,template如果是一个类名称的时候,那么这个类必须实现重载” <table cellspacing="0" cellpadding="2" width="777" border="1"><tbody><tr> <td valign="top" width="775"> <p>class Person <br>{ <br>public: <br> Person(const string& firstname,const string& lastname) <br> { <br> this->firstname=firstname; <br> this->lastname=lastname; <br> } <br>//如果没有const,那么下面的copy()会报告一堆错误,重载为const是一个好习惯 <br> friend ostream& operator { <br> os } <br>private: <br> string firstname ; <br> string lastname ; <br> friend class PersonSort; <br>}; <br>class PersonSort <br>{ <br>public: <br> bool operator()(const Person& p1,const Person& p2) const <br> { <br> return (p1.lastname<p2.lastname></p2.lastname> } <br>}; <br>int main() <br>{ <br> typedef set<person> PersonSet; <br> PersonSet ps; <br> ps.insert(Person("hongjian","chen")); <br> ps.insert(Person("lizhong","li")); <br> ps.insert(Person("xuan","liu")); <br>copy(ps.begin(),ps.end(),ostream_iterator<person>(cout,"/n")); <br>return 0; <br>}</person></person></p> </td> </tr></tbody></table> 另外、 <p>template<class _u class _e="char,"></class> class _Tr = char_traits<_e> > <br> class ostream_iterator <br> : public iterator<output_iterator_tag void></output_iterator_tag></_e></p> 从这段代码中亦可以发现,ostream_iterator继承iterator,iterator通过output_iterator_tag来标记定义的iterator为ostream适配器。 </template>