当前位置: 首页 > news >正文

(8)STL算法之替换

在STL算法中可以使用替换函数replace()、replace_if()完成替换操作。先来看下replace函数的底层实现。

// replace()  声明与实现
template <class ForwardIterator, class T>
void replace (ForwardIterator first, ForwardIterator last,const T& old_value, const T& new_value);

template <class ForwardIterator, class T>
void replace (ForwardIterator first, ForwardIterator last,const T& old_value, const T& new_value)
{
    while (first!=last) 
    {
        if (*first == old_value) 
            *first=new_value;
        ++first;
    }
}

再来看看replace_if()的底层实现...

template <class ForwardIterator, class UnaryPredicate, class T>
void replace_if (ForwardIterator first, ForwardIterator last,UnaryPredicate pred, const T& new_value );

template < class ForwardIterator, class UnaryPredicate, class T >
void replace_if (ForwardIterator first, ForwardIterator last,UnaryPredicate pred, const T& new_value)
{
    while ( first != last ) 
    {
        if ( pred( *first ) ) 
            *first = new_value;
        ++first;
    }
}

越看越觉得C语言真牛逼

这两个函数都是有条件的替换,replace()是将容器[first, last]范围中与old_value相等的元素,替换成new_value;而replace_if()是将容器[first, last]范围中能使函数pred为真的元素,替换成new_value。下来看一个例子。

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>   //  bind2nd(less<int>(), 7);
using namespace std;

void main()
{
	vector<int> v;
	int arr[] = { 1,2,3,4,5,6,7,8,9 };
	v.assign(arr, arr + 9);
	for (int val : v)
		cout << val << " ";   // 1 2 3 4 5 6 7 8 9
	cout << endl;
	replace(v.begin(),v.end(),5,10); //将等于 5 的元素替换成 10
	for (int val : v)
		cout << val << " ";   // 1 2 3 4 10 6 7 8 9
	cout << endl;
	replace_if(v.begin(), v.end(), bind2nd(less<int>(), 7), 11);  //将小于 7 的元素换成 11
	for (int val : v)
		cout << val << " ";   // 11 11 11 11 10 11 7 8 9
	cout << endl;
}

===========================================================================================================================================

再加两个替换函数replace_copy()、replace_copy_if()

template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy (InputIterator first, InputIterator last,OutputIterator result,const T& old_value, const T& new_value);

template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy (InputIterator first, InputIterator last,OutputIterator result,const T& old_value, const T& new_value)
{
    while (first!=last) 
    {
        *result = (*first==old_value)? new_value: *first;
        ++first; 
        ++result;
    }
    return result;
}
template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>
OutputIterator replace_copy_if (InputIterator first, InputIterator last,OutputIterator result, UnaryPredicate pred,const T& new_value);

template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>
OutputIterator replace_copy_if (InputIterator first, InputIterator last,OutputIterator result, UnaryPredicate pred,const T& new_value)
{
    while (first!=last) 
    {
        *result = ( pred(*first)) ? new_value : *first;
        ++first; 
        ++result;
    }
    return result;
}

用一个例子来学会它

#include <iostream>    
#include <algorithm>    
#include <vector>
using namespace std;

bool fun(int elem)
{
    return ((elem % 2 == 1));
}

int main() {
    int arr[] = { 10, 11, 12, 13, 14, 15, 11, 11 };
    vector<int> v1(8),v2;
    replace_copy(arr, arr + 8, v1.begin(), 11, 21);
    for (auto it = v1.begin(); it != v1.end(); ++it)
        cout << *it <<" ";    //  10 21 12 13 14 15 21 21
    cout << endl;
    v2.resize(v1.size());
    replace_copy_if(v1.begin(), v1.end(), v2.begin(), fun, 0);  //复制容器并将单数全部置 0 
    for (auto it = v2.begin(); it != v2.end(); ++it)
        cout << *it << " ";   //  10 0  12  0 14 0  0  0
    cout << endl;
    return 0;
}

 

相关文章:

  • (9)STL算法之逆转旋转
  • NFS安装使用
  • STL之map(关联式容器)
  • STL之unordered_map
  • 动态规划
  • 算法分析
  • 编写一个函数,实现将char类型的字符串,循环右移n个位置
  • 类构造、析构、赋值函数示例
  • 数组指针指针数组
  • LeeCode 20.有效的括号
  • LeeCode 26 删除排序数组中的重复项,返回数组新长度
  • LeeCode 27 移除元素,返回数组新长度
  • LeeCode 2125 合并两个(K个)有序链表
  • (10)STL算法之搜索(二) 二分查找
  • 单例模式(懒汉模式、饿汉模式)
  • 《剑指offer》分解让复杂问题更简单
  • 【Amaple教程】5. 插件
  • 11111111
  • 2018以太坊智能合约编程语言solidity的最佳IDEs
  • iOS编译提示和导航提示
  • Javascript设计模式学习之Observer(观察者)模式
  • MySQL常见的两种存储引擎:MyISAM与InnoDB的爱恨情仇
  • Promise面试题2实现异步串行执行
  • Python3爬取英雄联盟英雄皮肤大图
  • swift基础之_对象 实例方法 对象方法。
  • 从0实现一个tiny react(三)生命周期
  • 代理模式
  • 给初学者:JavaScript 中数组操作注意点
  • 机器人定位导航技术 激光SLAM与视觉SLAM谁更胜一筹?
  • 模仿 Go Sort 排序接口实现的自定义排序
  • 深度解析利用ES6进行Promise封装总结
  • 用quicker-worker.js轻松跑一个大数据遍历
  • RDS-Mysql 物理备份恢复到本地数据库上
  • 曾刷新两项世界纪录,腾讯优图人脸检测算法 DSFD 正式开源 ...
  • #pragma pack(1)
  • #多叉树深度遍历_结合深度学习的视频编码方法--帧内预测
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • (poj1.2.1)1970(筛选法模拟)
  • (第一天)包装对象、作用域、创建对象
  • ./mysql.server: 没有那个文件或目录_Linux下安装MySQL出现“ls: /var/lib/mysql/*.pid: 没有那个文件或目录”...
  • .NET 应用架构指导 V2 学习笔记(一) 软件架构的关键原则
  • .NetCore实践篇:分布式监控Zipkin持久化之殇
  • .net图片验证码生成、点击刷新及验证输入是否正确
  • @ComponentScan比较
  • [Android] Implementation vs API dependency
  • [BZOJ1089][SCOI2003]严格n元树(递推+高精度)
  • [BZOJ4554][TJOI2016HEOI2016]游戏(匈牙利)
  • [LeetCode]剑指 Offer 42. 连续子数组的最大和
  • [mysql]游标和触发器
  • [NOI2014]购票
  • [Qualcomm][Power]QCM2290功耗异常问题
  • [Spring Cloud 项目] Spring cloud 实现房源查询功能
  • [svc]对称加密/非对称加密细枝末节-如何做到数据传输的authentication/data integrity/confidentiality(私密)...
  • [Usaco2012 Dec]First! BZOJ3012
  • [Vuejs] 给ref赋值需要注意的问题