加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:06:56 所属栏目:百科 来源:网络整理
导读:copy:容器中指定元素拷贝到另一容器中 replace:将容器内指定范围内的旧元素改为新元素 replace_if:容器内指定范围为满足条件的元素替换为新元素 swap:互换两个容器的元素 1.copy #includeiostream using namespace std;#include vector #include algorit

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<v2;
    v2.resize(v1.size());
    copy(v1.begin(),v1.end(),v2.begin());

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

 main() {

    test01();

    system("pause);

    return 0;
}

2.replace

#include<iostream>

#include<algorithm>

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

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

    vector<v;
    v.push_back(20);
    v.push_back(30504010);

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


    将20 替换 2000
    replace(v.begin(),20,1)">2000);
    cout << 替换后:;
}

3.replace_if

#include<iostream>
 val)
    {    
        cout << val <<  Greater30
{
bool  val)
    {
        return val >= 常用拷贝和替换算法 replace_if
替换前:  endl;

    将大于等于30  替换为 3000
    replace_if(v.begin(),Greater30(),1)">3000替换后:  endl;

}

;
}

4.swap

#include<iostream>
常用拷贝和替换算法 swap
;
}
v1;
    vector<v2;

    )
    {
        v1.push_back(i);
        v2.push_back(i+100);
    }

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

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

    swap(v1,v2);

    for_each(v1.begin(),1)">;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读