zoukankan      html  css  js  c++  java
  • 泛型算法(九)之替换算法

    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,
  • 相关阅读:
    20151225jquery学习笔记---编辑器插件
    20151225jquery学习笔记---折叠菜单UI
    hihocoder1078 线段树的区间修改
    hihocoder1067 最近公共祖先·二
    poj1857 To Europe! To Europe!
    PKU_campus_2017_K Lying Island
    PKU_campus_2018_H Safe Upper Bound
    PKU_campus_2018_D Chocolate
    poj3254 Corn Fields
    poj2441 Arrange the Bulls
  • 原文地址:https://www.cnblogs.com/dongerlei/p/5142065.html
Copyright © 2011-2022 走看看