• 泛型算法(九)之替换算法


    1、replace(ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value):把序列中为给定值的元素替换为新值

        std::vector<int> c;
        c.reserve(10);
        //向c中添加元素
        for (int i = 0; i < 10; i++)
        {
            c.push_back(i);
        }
        //把序列c中值等于5的元素替换成100
        std::replace(c.begin(), c.end(), 5, 100);
        //输出c
        for (auto var : c)
        {
            std::cout << var << ",";
        }
        //打印结果:0,1,2,3,4,100,6,7,8,9,

    2、replace_if(ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value):把序列中满足给定谓词pred的元素替换为新值

        std::vector<int> c;
        c.reserve(10);
        //向c中添加元素
        for (int i = 0; i < 10; i++)
        {
            c.push_back(i);
        }
        //把序列c中值大于5的元素替换成100
        std::replace_if(c.begin(), c.end(), [](int element){
            return element > 5;
        }, 100);
        //输出c
        for (auto var : c)
        {
            std::cout << var << ",";
        }
        //打印结果:0,1,2,3,4,5,100,100,100,100,

    3、replace_copy(InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value)复制序列,对于等于老值的元素复制时使用新值

        std::vector<int> c;
        std::vector<int> result;
        c.reserve(10);
        result.resize(10);
        //向c中添加元素
        for (int i = 0; i < 10; i++)
        {
            c.push_back(i);
        }
        //复制c到result中,对于c中等于5的元素在复制时用100代替
        std::replace_copy(c.begin(), c.end(), result.begin(), 5, 100);
        //输出result
        for (auto var : result)
        {
            std::cout << var << ",";
        }
        //打印结果:0,1,2,3,4,100,6,7,8,9,

    4、replace_copy_if(InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred, const T& new_value):复制序列,对于满足给定谓词pred的元素复制新值

        std::vector<int> c;
        std::vector<int> result;
        c.reserve(10);
        result.resize(10);
        //向c中添加元素
        for (int i = 0; i < 10; i++)
        {
            c.push_back(i);
        }
        //复制c到result中,对于c中大于5的元素在复制时用100代替
        std::replace_copy_if(c.begin(), c.end(), result.begin(), [](int element){
            return element > 5;
        }, 100);
        //输出result
        for (auto var : result)
        {
            std::cout << var << ",";
        }
        //打印结果:0,1,2,3,4,5,100,100,100,100,
  • 相关阅读:
    我理解的Node.js
    How to handle the issue of node.js msi to roll back under windows 8
    转:.Net 中AxShockwaveFlash的解析
    鱼哥的C++学习笔记(一)编译方法
    TabControl样式编写
    Cocos2d on VS12 step by step
    C# 控制Windows系统音量
    系统环境换成Win8+Vs2012碰到的问题记录
    Http学习笔记(一)
    WPF ListBox Template解析
  • 原文地址:https://www.cnblogs.com/dongerlei/p/5142065.html
Copyright © 2020-2023  润新知