1.STL基本概念
●STL(Standard Template Libray 标准模板库)
●STL在广义上分为:容器,算法,迭代器
●容器和算法之间通过迭代器进行无缝连接
●STL几乎所有的代码都采用了模板类或者模板函数
2.STL六大组件
1.容器:各种数据结构
2.算法(algorithms):
3.迭代器(iterator):
4.:仿函数
5.适配器
6.空间适配器
3.STL中容器、算法、迭代器
容器:
序列式容器:强调值的排序,每个元素均有固定位置
关联式容器:二叉树结构,各元素之间没有严格的物理上的顺序关系。
算法:问题之解法。
质变算法:在运算过程中会改变区间内元素的内容
非质变算法:在运算过程中不会改变区间内元素的内容。
迭代器:容器和算法的粘合剂
双向迭代器:
随机访问迭代器:
4.初识迭代器
STL最常用的容器为vector,可以理解为数组。
容器: vector
算法: for_each
迭代器:vector< int >::iterator
第一种遍历方式:
代码如下:用whiile循环实现
void test01(){
int n;
//创建vector 容器对象,并且通过模板参数指定容器中存放的数据类型
vector<int> a;
//向容器中存放数据
cout<<"请输入3个整数"<<endl;
for(int i=0;i<3;i++){
cin>>n;
a.push_back(n);
}
cout<<"输出:"<<endl;
//每一个容器都有自己的迭代器,迭代器是用来遍历容器中的元素
//a.begin()返回迭代器,这个迭代器指向容器中第一个数据
//a.end()返回迭代器,这个迭代器指向容器元素的最后一个元素的下一个位置
//更换开始位置
vector<int>::iterator pbegin=a.begin();
vector<int>::iterator pend=a.end();
while(pbegin!=pend){
cout<<*pbegin<<endl;
pbegin++;
}
//更换结束位置
}
第二种遍历方式:
用for循环实现(这种最常用)
更换代码如下:
for(vector<int>::iterator it=a.begin();it!=a.end();it++){
cout<<*it<<endl;
}
第三种遍历方式:
使用STL踢狗标准遍历算法,头文件algorithm
用函数for_each()。(自己感觉最简单的遍历方式)
for_each(a.begin(),a.end(),myprint);
myprint------>就是个简单的自定义输出函数。
如下:
void myprint(int n){
cout<<n<<endl;
}
容器vector可以存放自定义数据
比如对象,指针等。
代码示例:
#include<iostream>
#include<vector>
#include<algorithm>
#include <string>
using namespace std;
class Person{
public:
Person(string name,int age){
this->name=name;
this->age=age;
}
string name;
int age;
};
void test01(){
int i=0,page;
string pname;
vector<Person> a;
cout<<"请输入:"<<endl;
for(i;i<2;i++){
cout<<i<<".姓名:";
cin>>pname;
cout<<"年龄:";
cin>>page;
a.push_back(Person(pname,page));
}
// vector<Person>::iterator it=a.begin();
// vector<Person>::iterator is=a.end();
for(vector<Person>::iterator it=a.begin();it!=a.end();it++){
cout<<(*it).name<<(*it).age<<endl;
}
}
int main(){
test01();
return 0;
}
略略略略::::::。 。。。
容器嵌套容器
其实就是套娃的思想