当前位置: 首页 > 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算法之搜索(二) 二分查找
  • 单例模式(懒汉模式、饿汉模式)
  • Essential Studio for ASP.NET Web Forms 2017 v2,新增自定义树形网格工具栏
  • happypack两次报错的问题
  • Logstash 参考指南(目录)
  • PHP面试之三:MySQL数据库
  • Python十分钟制作属于你自己的个性logo
  • react 代码优化(一) ——事件处理
  • Spring Cloud Alibaba迁移指南(一):一行代码从 Hystrix 迁移到 Sentinel
  • spring学习第二天
  • WinRAR存在严重的安全漏洞影响5亿用户
  • 编写高质量JavaScript代码之并发
  • 仿天猫超市收藏抛物线动画工具库
  • 思否第一天
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 微信小程序设置上一页数据
  • 微信小程序填坑清单
  • Prometheus VS InfluxDB
  • Spring Batch JSON 支持
  • 浅谈sql中的in与not in,exists与not exists的区别
  • 昨天1024程序员节,我故意写了个死循环~
  • ​sqlite3 --- SQLite 数据库 DB-API 2.0 接口模块​
  • ​如何使用ArcGIS Pro制作渐变河流效果
  • #{}和${}的区别?
  • #{}和${}的区别是什么 -- java面试
  • #define 用法
  • (delphi11最新学习资料) Object Pascal 学习笔记---第7章第3节(封装和窗体)
  • (Redis使用系列) Springboot 实现Redis消息的订阅与分布 四
  • (八)五种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (三)终结任务
  • (转) RFS+AutoItLibrary测试web对话框
  • ./和../以及/和~之间的区别
  • .NETCORE 开发登录接口MFA谷歌多因子身份验证
  • .NET构架之我见
  • .NET框架
  • .NET使用HttpClient以multipart/form-data形式post上传文件及其相关参数
  • .NET学习教程二——.net基础定义+VS常用设置
  • @NoArgsConstructor和@AllArgsConstructor,@Builder
  • [2016.7.test1] T2 偷天换日 [codevs 1163 访问艺术馆(类似)]
  • [20180129]bash显示path环境变量.txt
  • [AIGC] Java List接口详解