Copy算法与ostream_iterator结合可以用于输出某个容器的元素
copy 函数模板(算法)
template<class InIt, class OutIt>
OutIt copy(InIt first, InIt last, OutIt x);
本函数对每个在区间[0, last - first)中的N执行一次
*(x+N) = *(first + N), 返回 x + N
对于copy(v.begin(),v.end(),output);
first 和 last 的类型是 vector::const_iterator
output 的类型是 ostream_iterator
copy 的源代码:
template<class _II, class _OI>
inline _OI copy(_II _F, _II _L, _OI _X)
{
for (; _F != _L; ++_X, ++_F)
*_X = *_F;
return (_X);
}
ostream_iterator
ostream_iterator<int> output(cout ,“ ”);
定义了一个 ostream_iterator 对象,
可以通过cout输出以 “ ”(空格) 分隔的一个个整数
copy (v.begin(), v.end(), output);
导致v的内容在 cout上输出
示例
#include <vector>
#include <iostream>
#include <numeric>
#include <list>
#include <algorithm>
#include <iterator>
using namespace std;
class CLessThen9 {
public:
bool operator()( int n) { return n < 9; }
};
void outputSquare(int value ) { cout << value * value << " "; }
int calculateCube(int value) { return value * value * value; }
int main() {
const int SIZE = 10;
int a1[] = { 1,2,3,4,5,6,7,8,9,10 };
int a2[] = { 100,2,8,1,50,3,8,9,10,2 };
vector<int> v(a1,a1+SIZE);
ostream_iterator<int> output(cout," ");
random_shuffle(v.begin(),v.end());
cout << endl << "1) ";
copy( v.begin(),v.end(),output);
copy( a2,a2+SIZE,v.begin());
cout << endl << "2)";
cout << count(v.begin(),v.end(),8);
cout << endl << "3)";
cout << count_if(v.begin(),v.end(),CLessThen9());
cout << endl << "4) ";
cout << * (min_element(v.begin(), v.end()));
cout << endl << "5) ";
cout << * (max_element(v.begin(), v.end()));
cout << endl << "6) ";
cout << accumulate(v.begin(), v.end(), 0); //求和
cout << endl << "7) ";
for_each(v.begin(), v.end(), outputSquare);
vector<int> cubes(SIZE);
transform(a1, a1+SIZE, cubes.begin(), calculateCube);
cout << endl << "8) ";
copy(cubes.begin(), cubes.end(), output);
return 0;
}
输出:
- 5 4 1 3 7 8 9 10 6 2
- 2
- 6
//1) 是随机的 - 1
- 100
- 193
- 10000 4 64 1 2500 9 64 81 100 4
- 1 8 27 64 125 216 343 512 729 1000
如何编写一个和ostream_iterator一样的类My_ostream_iterator?
My_ostream_iterator类应该重载 “++” 和 “*” 运算符
“=” 也应该被重载
#include <iterator>
template<class T>
class My_ostream_iterator:public iterator<output_iterator_tag, T>{
private:
string sep; //分隔符
ostream & os;
public:
My_ostream_iterator(ostream & o, string s):sep(s), os(o){ }
void operator ++() { }; // ++只需要有定义即可, 不需要做什么
My_ostream_iterator & operator * () { return * this; }
My_ostream_iterator & operator = ( const T & val)
{ os << val << sep; return * this; }
};
使用自己编写的My_ostream_iterator和copy函数示例
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main(){
int a[4] = { 1,2,3,4 };
My_ostream_iterator<int> oit(cout,"*");
copy(a,a+4,oit); //输出 1*2*3*4*
ofstream oFile("test.txt", ios::out);
My_ostream_iterator<int> oitf(oFile,"*");
copy(a,a+4,oitf); //向test.txt文件中写入 1*2*3*4*
oFile.close();
return 0;}