博客
关于我
【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/

你可能感兴趣的文章
nginx + etcd 动态负载均衡实践(一)—— 组件介绍
查看>>
nginx + etcd 动态负载均衡实践(三)—— 基于nginx-upsync-module实现
查看>>
nginx + etcd 动态负载均衡实践(二)—— 组件安装
查看>>
nginx + etcd 动态负载均衡实践(四)—— 基于confd实现
查看>>
Nginx + Spring Boot 实现负载均衡
查看>>
Nginx + Tomcat + SpringBoot 部署项目
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
Nginx - 反向代理与负载均衡
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx 301跳转
查看>>
nginx 403 forbidden
查看>>
nginx connect 模块安装以及配置
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
nginx http配置说明,逐渐完善。
查看>>
Nginx keepalived一主一从高可用,手把手带你一步一步配置!
查看>>