c/c++:copy 和transform的使用

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <sstream>
#include <deque>

using namespace std;

int fun1(int value)
{
    return value*2;
}

int fun2(int value1,int value2)
{
    return value1+value2;
}


template<class T>
class A
{
};

template<>
class A<string>
{
    public:
    string operator() (const string & src)
    {
        string s=src;
        for(string::iterator it=s.begin();it!=s.end();it++)
            *it = (*it)+1;
        return s;
    }
};

int main()
{
    int a[5]={1,2,3,4,5};
    vector<int > b(5,10);
    int c[5];
    copy(a,a+5,ostream_iterator<int>(cout,"|"));
    cout<<endl;
    copy(b.begin(),b.end(),ostream_iterator<int>(cout,"|"));
    cout<<endl;
    transform(a,a+5,c,fun1);
    copy(c,c+5,ostream_iterator<int>(cout,"|"));
    cout<<endl;
    transform(a,a+5,b.begin(),c,fun2);//注意,b 是向量,所以要用.begin()
    copy(c,c+5,ostream_iterator<int>(cout,"|"));
    cout<<endl;

    vector<string > v;
    vector<string > vresult;
    deque<string > v2result;
    v.push_back("aaa");
    v.push_back("bbb");
    v.push_back("ccc");
    v.push_back("ddd");
    transform(v.begin(),v.end(),back_inserter(vresult),A<string>());//back_inserter 将数据插入到参数的尾部,因为vector 不支持push_front
    transform(v.begin(),v.end(),front_inserter(v2result),A<string>());//不能直接写 .begin(),一定要用到front_inserter或back_
    copy(vresult.begin(),vresult.end(),ostream_iterator<string>(cout,"|"));
    cout<<endl;
    copy(v2result.begin(),v2result.end(),ostream_iterator<string>(cout,"|"));
    cout<<endl;




    return 0;
}
posted @ 2012-07-11 15:45  A_zhu  阅读(2345)  评论(0编辑  收藏  举报