博客
关于我
【C++系列】C++中的 常用拷贝和替换算法
阅读量:236 次
发布时间:2019-03-01

本文共 1592 字,大约阅读时间需要 5 分钟。

常用拷贝和替换算法

学习目标:

  • 掌握常用的拷贝和替换算法

算法简介:

  • copy // 容器内指定范围的元素拷贝到另一容器中
  • replace // 将容器内指定范围的旧元素修改为新元素
  • replace_if // 容器内指定范围满足条件的元素替换为新元素
  • swap // 互换两个容器的元素

5.4.1 copy

功能描述:

  • 容器内指定范围的元素拷贝到另一容器中

函数原型:

  • copy(iterator beg, iterator end, iterator dest);
  • 注:
    beg是起始迭代器,
    end是结束迭代器,
    dest是目标容器的起始迭代器。

示例:

#include #include #include using namespace std; class myPrint {public:void operator()(int val) {cout << val << " ";}}; void test01() {vector v1 = {1, 2, 3, 4, 5};vector v2;copy(v1.begin(), v1.end(), back_inserter(v2));cout << "v2: ";myPrint p;for_each(v2.begin(), v2.end(), p);cout << endl;}

5.4.2 replace

功能描述:

  • 将容器内指定范围内的旧元素替换为新值

函数原型:

  • replace(iterator begin, iterator end, const T& value);

示例:

#include #include #include using namespace std; void test02() {vector v1 = {1, 2, 3, 4, 5};replace(v1.begin(), v1.end(), 10);cout << "v1: ";for (int val : v1) {cout << val << " ";}cout << endl;}

5.4.3 replace_if

功能描述:

  • 在容器内指定范围内,满足条件的元素替换为新值

函数原型:

  • replace_if(iterator begin, iterator end, Pred pred, const T& value);

示例:

#include #include #include #include using namespace std; void test03() {vector v1 = {1, 2, 3, 4, 5};replace_if(v1.begin(), v1.end(), not_less(5), 10);cout << "v1: ";for (int val : v1) {cout << val << " ";}cout << endl;}

5.4.4 swap

功能描述:

  • 互换两个容器中的元素

函数原型:

  • swap(iterator& begin, iterator& end, Container& other);

示例:

#include #include #include using namespace std; void test04() {vector v1 = {1, 2, 3};vector v2 = {4, 5, 6};swap(v1.begin(), v1.end(), v2.begin(), v2.end());cout << "v1: ";for (int val : v1) {cout << val << " ";}cout << "v2: ";for (int val : v2) {cout << val << " ";}cout << endl;}

转载地址:http://esxv.baihongyu.com/

你可能感兴趣的文章
MySQL - 解读MySQL事务与锁机制
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>