常用的拷贝和替换算法

shienh 2020年02月09日 197次浏览
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

//copy
void test1(){
    vector<int> v1;
    vector<int> des;
    for(int i = 0; i < 10; i++){
        v1.push_back(i);
    }
    des.resize(v1.size());
    copy(v1.begin(),v1.end(),des.begin());
    for_each(des.begin(),des.end(),[](int val){cout<<val<<" ";});
    cout<<endl;
}

//replace
void test2(){
    vector<int> v;
    for(int i =0 ; i < 10; i++){
        v.push_back(i);
    }
    replace(v.begin(),v.end(),3,300);
    for_each(v.begin(),v.end(),[](int val){cout<<val<<" ";});
    cout<<endl;
}

class Compare{
public:
    bool operator ()(int val){
            return val > 3;
    }
};

//replace_if
void test3(){
    vector<int> v;
    for(int i =0 ; i < 10; i++){
        v.push_back(i);
    }
  //将所有大于3的值替换为3000
    replace_if(v.begin(),v.end(),Compare(),3000);
    for_each(v.begin(),v.end(),[](int val){cout<<val<<" ";});
    cout<<endl;
}


//swap
void test4(){
    vector<int> v1;
    for(int i = 0; i < 10;i++){
        v1.push_back(i);
    }
    vector<int> v2(11,100);
    swap(v1,v2);

    for_each(v1.begin(),v1.end(),[](int val){cout<<val<<" ";});
    cout<<endl;

    for_each(v2.begin(),v2.end(),[](int val){cout<<val<<" ";});
    cout<<endl;
}
int main(int argc, char *argv[])
{
    test1();
    test2();
    test3();
    test4();
    return 0;
}