拷贝和替换算法操作指南

拷贝和替换算法操作指南

#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>
void myprint3(int val)
{
    cout << val << " ";
}

//一、replace
/*
replace(iterator beg, iterator end, oldvalue, newvalue);
将容器内指定范围的旧元素修改为新元素
beg开始迭代器
end结束迭代器
oldvalue旧元素
newvalue新元素
*/
void t0001()
{
    vector<int> v;
    v.push_back(20);
    v.push_back(50);
    v.push_back(60);
    v.push_back(20);
    v.push_back(20);
    v.push_back(20);
    v.push_back(40);
    v.push_back(20);
    cout << "替换前" << endl;
    for_each(v.begin(), v.end(), myprint3);
    cout << endl;
    replace(v.begin(), v.end(), 20, 2000);
    cout << "替换后" << endl;
    for_each(v.begin(), v.end(), myprint3);
}

//二、replace_if
/*
replace_if(iterator beg, iterator end, _pred, newvalue)
将容器内指定范围满足条件的元素修改为新元素
beg开始迭代器
end结束迭代器
_pred条件谓词
newvalue新元素
*/
class compare
{
public:
    bool operator()(int val)
    {
        return val > 50;
    }
};
void t0002()
{
    vector<int> v;
    v.push_back(20);
    v.push_back(50);
    v.push_back(60);
    v.push_back(20);
    v.push_back(20);
    v.push_back(20);
    v.push_back(40);
    v.push_back(20);
    cout << "替换前" << endl;
    for_each(v.begin(), v.end(), myprint3);
    cout << endl;
    replace_if(v.begin(), v.end(), compare(), 2000);
    cout << "替换后" << endl;
    for_each(v.begin(), v.end(), myprint3);
}

//三、swap
/*
swap(container c1, container c2);
互换两个同类型的容器的元素
*/
void t0003()
{
    vector<int> v1;
    vector<int> v2;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    for (int i = 0; i < 100; i++)
    {
        v2.push_back(i + 100);
    }
    for_each(v1.begin(), v1.end(), myprint3);
    cout << endl;
    swap(v1, v2);//这个就不需要提前分配空间了
    for_each(v1.begin(), v1.end(), myprint3);
}

//四、copy
/*
copy(iterator beg, iterator end, iterator dest);
beg开始迭代器
end结束迭代器
dest目标起始迭代器
*/ 
void t0004()
{
    vector<int> v1;
    vector<int> v2;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
    }
    v2.resize(v1.size());//提前给目标容器开辟空间
    copy(v1.begin(), v1.end(), v2.begin());
    for_each(v2.begin(), v2.end(), myprint3);
}

int main_copy()
{
    t0003();
    return 0;
}

 

------------恢复内容结束------------

上一篇:[LeetCode&Python] Problem 202. Happy Number


下一篇:springboot之yaml使用