1 泛型程序设计基本概念
1 概念
![在这里插入图片描述](https://img-blog.csdnimg.cn/a9b1e2c63b764d89902772d591a8ad44.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDQ3ODY1OQ==,size_16,color_FFFFFF,t_70)
2 模型
![在这里插入图片描述](https://img-blog.csdnimg.cn/2e88dbd4984f467abb476ba49037fe47.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/1068513f26f7422ab785f834a337e3fc.png)
3 模板参数的命名:使用概念
![在这里插入图片描述](https://img-blog.csdnimg.cn/21cfc5845dfc466082c24aebd4841ab5.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDQ3ODY1OQ==,size_16,color_FFFFFF,t_70)
2 STL
STL基本组件:容器(container)、迭代器(iterator)、函数对象(function object)、算法(algorithms)
iterator相当于容器的指针
容器 container
迭代器 iterator
函数对象 function object
![在这里插入图片描述](https://img-blog.csdnimg.cn/1b901ce2cca441d190f95fa7c18270bb.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDQ3ODY1OQ==,size_16,color_FFFFFF,t_70)
算法 algorithms
![在这里插入图片描述](https://img-blog.csdnimg.cn/94aa6124981d4ec6a392e13e4a6c31ee.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDQ3ODY1OQ==,size_16,color_FFFFFF,t_70)
STL程序实例
通过STL中的transform输出相反数
#include<iostream>
#include<vector> //容器
#include<iterator> //迭代器
#include<algorithm> //算法
#include<functional> //函数对象
using namespace std;
int main() {
const int N = 5; //通过const定义常量,取代#define
vector<int> s(N); //容器为vector,int类型,s为容器名称
for (int i = 0; i < N; i++)
cin >> s[i];
transform(s.begin(), s.end(), ostream_iterator<int>(cout, " 2 "), negate<int>());
//begin()、end()是指向向量开头和结尾的迭代器
//ostream_iterator是输出流迭代器,将结果依次送到输出流中
//negate为求相反数的函数方法
cout << endl;
return 0;
}
transform算法的实现
template<class InputInterator, class OutputInterator, class UnaryFunction>
//自定义三个类型,类型名称为概念,即输入迭代器-输出迭代器-一元函数
OutputInterator transform(InputInterator first, InputInterator last,
OutputInterator result, UnaryFunction op) {
for (; first != last; first++, result++) //for循环没有起始条件,每轮更新输入迭代器和结果迭代器
*result = op(*first); //注意要用*使用迭代器指向的元素
//每次循环,结果为算法函数处理输入元素的结果
return result; //所有结果更新完毕后返回
}