美文网首页
黑马C++视频笔记《STL之拷贝与替换》

黑马C++视频笔记《STL之拷贝与替换》

作者: 井底蛙蛙呱呱呱 | 来源:发表于2021-01-27 00:04 被阅读0次
/* 常用拷贝和替换算法
 *
 * copy
 * 将容器中指定范围内的元素拷贝到另一容器中;
 * 函数原型:`copy(iterator beg, iterator end, iterator dest beg);`;
 *  - iterator beg 和 iterator end指定要复制的源容器的范围;
 *  - iterator dest beg目标容器迭代器起始位置;
 * 注:这里需要先给目标容器开辟空间储存复制的元素.
 *
 *
 * replace
 * 将容器指定范围内的旧元素替换为新元素;
 * 函数原型:`replace(iterator beg, iterator end, old, new);`
 *  - iterator beg 和 iterator end指定要替换的元素的范围;
 *  - old 和 new 指定替换值;
 *
 *
 * replace_if
 * 将区间内满足条件的元素替换成指定元素;
 * 函数原型:`replace_if(iterator beg, iterator end, _Pred, newvalue);`;
 *  - iterator beg 和 iterator end指定要替换的元素的范围;
 *  - _Pred 谓词判断哪些元素要替换;
 *  - newvalue指定要替换的新值;
 *
 *
 * swap
 * 互换两个容器的元素
 * 函数原型:`swap(container1, container2);`;
 *  - container1, container2 两个待交换的容器;
 * 注:
 *  (1)这里需要先给目标容器开辟空间储存复制的元素;
 *  (2)两个容器元素类型应该相同;
 */

一个栗子:

#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <algorithm>
#include <random>

using namespace std;

// 一元谓词
class GT500{

public:
    GT500(int mark){
        this->m_mark = mark;
    }
    bool operator()(int val){
        return val>this->m_mark;
    }

    int m_mark;
};


void CreateVec(vector<int> &v){
    // srand((unsigned int)time(NULL)); 旧版生成随机数方法,弃用
    std::random_device rd; // Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dist(0, 1000);
    for(int i=0; i<10; i++){
        int a  = dist(gen); // 使用新的产生随机数的方式
        v.push_back(a);
    }
}

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

int main(){
    vector<int> v1;
    vector<int> v2;
    CreateVec(v1);
    cout << "容器1:" << endl;
    for_each(v1.begin(), v1.end(), myPrint());
    cout << endl;

    // 拷贝
    cout << "替换前:" << endl;
    v2.resize(v1.size());
    copy(v1.begin(), v1.end(), v2.begin());
    for_each(v2.begin(), v2.end(), myPrint());
    cout << endl;

    // 替换
    cout << "替换后:" << endl;
    replace_if(v2.begin(), v2.end(), GT500(500), 1000);
    for_each(v2.begin(), v2.end(), myPrint());
    cout << endl;

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

输出:

容器1:
856 487 227 911 489 173 420 972 911 591 
替换前:
856 487 227 911 489 173 420 972 911 591 
替换后:
1000 487 227 1000 489 173 420 1000 1000 1000 
swap v1 v2前:
856 487 227 911 489 173 420 972 911 591 
1000 487 227 1000 489 173 420 1000 1000 1000 
swap v1 v2后:
1000 487 227 1000 489 173 420 1000 1000 1000 
856 487 227 911 489 173 420 972 911 591 

网友评论

      本文标题:黑马C++视频笔记《STL之拷贝与替换》

      本文链接:https://www.haomeiwen.com/subject/xgwmzktx.html