c++STL之常用拷贝和替换算法

copy:容器中指定元素拷贝到另一容器中

replace:将容器内指定范围内的旧元素改为新元素

replace_if:容器内指定范围为满足条件的元素替换为新元素

swap:互换两个容器的元素

1.copy

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>

//常用拷贝和替换算法 copy
void myPrint(int val)
{
    cout << val << " ";
}

void test01()
{
    vector<int>v1;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }

    vector<int>v2;
    v2.resize(v1.size());
    copy(v1.begin(), v1.end(), v2.begin());

    for_each(v2.begin(), v2.end(), myPrint);
    cout << endl;
}

int main() {

    test01();

    system("pause");

    return 0;
}

2.replace

#include<iostream>
using namespace std;
#include <vector>
#include<algorithm>

class MyPrint
{
public:
    void operator()(int val)
    {
        cout << val << " ";
    }
};

//常用拷贝和替换算法 replace
void test01()
{

    vector<int>v;
    v.push_back(20);
    v.push_back(30);
    v.push_back(50);
    v.push_back(30);
    v.push_back(40);
    v.push_back(20);
    v.push_back(10);
    v.push_back(20);

    cout << "替换前:" << endl;
    for_each(v.begin(), v.end(), MyPrint());
    cout << endl;


    //将20 替换 2000
    replace(v.begin(), v.end(), 20, 2000);
    cout << "替换后:" << endl;
    for_each(v.begin(), v.end(), MyPrint());
    cout << endl;
}

int main() {

    test01();

    system("pause");

    return 0;
}

3.replace_if

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>

class MyPrint
{
public:
    void operator()(int val)
    {    
        cout << val << " ";
    }
};

class Greater30
{
public:
    bool operator()(int val)
    {
        return val >= 30;
    }
};

//常用拷贝和替换算法 replace_if
void test01()
{
    vector<int>v;
    v.push_back(10);
    v.push_back(40);
    v.push_back(20);
    v.push_back(40);
    v.push_back(30);
    v.push_back(50);
    v.push_back(20);
    v.push_back(30);

    cout << "替换前: " << endl;
    for_each(v.begin(), v.end(), MyPrint());
    cout << endl;

    //将大于等于30  替换为 3000
    replace_if(v.begin(), v.end(), Greater30(),3000);
    cout << "替换后: " << endl;
    for_each(v.begin(), v.end(), MyPrint());
    cout << endl;

}

int main() {

    test01();

    system("pause");

    return 0;
}

4.swap

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm>

//常用拷贝和替换算法 swap
void myPrint(int val)
{
    cout << val << " ";
}
void test01()
{
    vector<int>v1;
    vector<int>v2;

    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
        v2.push_back(i+100);
    }

    cout << "交换前: " << endl;
    for_each(v1.begin(), v1.end(), myPrint);
    cout << endl;
    for_each(v2.begin(), v2.end(), myPrint);
    cout << endl;

    cout << "-----------------" << endl;
    cout << "交换后: " << endl;

    swap(v1, v2);

    for_each(v1.begin(), v1.end(), myPrint);
    cout << endl;
    for_each(v2.begin(), v2.end(), myPrint);
    cout << endl;

}

int main() {

    test01();

    system("pause");

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/12114778.html