初步感受一下泛型算法---以accumulate作用于内置数组、vector和list为例
来源:互联网 发布:机房迁移网络方案 编辑:程序博客网 时间:2024/06/06 12:31
我们已经对C++ STL有一点了解了, 比如vector, list等等, 但是, 这些标准数据结构定义的操作是非常有限的,当然啦, 内置数组的操作也很少。 假设现在有这样一个需求, 要求内置数组的元素和, 求vector中的元素和, 求list中的元素和, 难道我们要搞三个算法吗? 非也, 我们可以引进泛型算法。 什么叫泛型算法呢? 其实, 泛型算法独立于特定的容器, 是对数据结构类型的抽象, 也就是说, 我不管你数据结构是咋样的, 我这个算法能够通用。
下面, 我们来看看非常简单的一个例子, 以便感受一下泛型算法:
#include <iostream>#include <vector>#include <list>#include <string>#include <numeric> // 泛型算法函数accumulateusing namespace std;int main(){int a[10] = {0};int i = 1;for(i = 0; i < 10; i++){a[i] = i + 1;}cout << accumulate(a, a + 10, 0) << endl; // 针对内置数组vector<int> v;for(i = 0; i < 10; i++){v.push_back(i + 1);}cout << accumulate(v.begin(), v.end(), 0) << endl; // 针对C++ STL vectorlist<int> L;for(i = 0; i < 10; i++){L.push_back(i + 1);}cout << accumulate(L.begin(), L.end(), 0) << endl; // 针对C++ STL listreturn 0;}我们看到, 无论是对于内置数组, 还是vector, 还是list, 我们都是用的accumulate这一个函数, 这就是所谓的泛型算法(函数)。 通过本例, 我们可以感知到泛型算法的魅力和威力。 以后, 我们还会对泛型算法作更多的介绍, 让我们拭目以待。
1 0
- 初步感受一下泛型算法---以accumulate作用于内置数组、vector和list为例
- STL泛型算法--accumulate()
- 泛型算法之——accumulate和find_first_of
- 泛型算法系列1:accumulate()
- 泛型算法系列(01)accumulate()
- C++泛型算法中的accumulate
- 动态数组vector和List
- 动态数组vector和List
- el和jsp内置对象的作用于
- jsp 四大作用于和九大内置对象
- C++ list vector 和 数组 的区别
- C#2.0模拟List和内置算法
- c++ std - accumulate 求数组和
- accumulate算法
- Ubuntu中/etc/apt/sources.list.d目录的作用(以Ubuntu12.04为例)
- 比较vector和list的排序算法
- vector和string优先于动态分配的数组
- vs2010下关于vector和动态数组的效率区别
- 数组 Remove Duplicates from Sorted Array II
- 关于 wps for linux的卸载
- Linux入侵检查实用指令
- 组队赛#2解题总结 (BNU 第十一届北京师范大学程序设计竞赛)
- 汇编学习之路之CS 和 IP
- 初步感受一下泛型算法---以accumulate作用于内置数组、vector和list为例
- 每日一得--*.PFX(*.p12)&个人信息交换文件
- git core.autocrlf配置 解决Windows和Linux(Mac)换行问题
- HDU 2222 Keywords Search【AC自动机|字典树】
- 46. PHP for
- 随笔
- 学习笔记
- CPU acceleration status: HAX kernel module is not installed!
- mac 安装Django