STL中最常用的容器是vector,可以理解为数组。
用法介绍:
1.vector<类型>标识符
//int型vector
vector<int> vectInt;
2.vector<类型>标识符(最大容量)
//int型vector,包含3个元素
vector<int> vecIntA(3);
3.vector<类型>标识符(最大容量,初始所有值)
//int型vector,包含3个元素且每个元素都是9
vector<int> vecIntB(3,9);
4.vector<vector<类型>>标识符
//容器嵌套容器 嵌套int型vector
vector<vector<int>> vectNested
头文件:#include <vector>
容器: vector
算法: for_each()
迭代器:vector<int>::iterator
示例代码(向容器中插入数据,遍历数据):
1.内置数据类型Demo
#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>//标准算法头文件
void my_Print(int val)
{
cout << val << " ";
putchar('\n');
}
void vector_Demo()
{
//创建一个vector容器,数组
vector<int> v;
//向容器中插入数据
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
vector<int>::iterator itBegin = v.begin();//起始迭代器,指向容器中的第一个元素
vector<int>::iterator itEnd = v.end();//结束迭代器,指向容器中最后一个元素的下一个位置
//第一种遍历方式,通过迭代器
/*for(itBegin ;itBegin != itEnd;itBegin++)
{
cout << *itBegin << " ";
}
putchar('\n');*/
//第二种遍历方式,利用STL提供的遍历算法 for_each()
for_each(itBegin,itEnd,my_Print);
}
int main()
{
vector_Demo();
return 0;
}
2.自定义数据类型Demo
#include <iostream>
using namespace std;
#include <vector>
#include <string>
//自定义数据类型
class Person
{
public:
Person(string name,int age)
{
this->my_Name = name;
this->my_Age = age;
}
string my_Name;
int my_Age;
};
void vector_Demo()
{
vector<Person> v;
Person p1("小李子",18);
Person p2("小福贵",17);
//插入数据
v.push_back(p1);
v.push_back(p2);
//遍历
for(vector<Person>::iterator it = v.begin(); it != v.end(); it++)
{
cout << "姓名:"<< (*it).my_Name <<"\t"<< "年龄:"<< (*it).my_Age <<endl;
//cout << "姓名:"<< it->my_Name <<"\t"<< "年龄:"<< it->my_Age <<endl;
}
putchar('\n');
}
int main(int argc, char const *argv[])
{
vector_Demo();
return 0;
}
3.容器嵌套容器Demo
#include <iostream>
using namespace std;
#include <vector>
void vector_Nested()
{
//容器嵌套容器
vector <vector <int>> v;
//小容器
vector <int> v1;
vector <int> v2;
vector <int> v3;
//向小容器中插入数据
for(int i = 0;i < 3 ;i++)
{
v1.push_back(i+1);
v2.push_back(i+2);
v3.push_back(i+3);
}
//将小容器插入到大容器中
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
for(vector <vector <int>>::iterator it = v.begin(); it != v.end(); it++)
{
//(*it) 可以理解为嵌套里面的vector <int>
for(vector <int>::iterator nestedIt = (*it).begin();nestedIt != (*it).end();nestedIt++ )
{
cout << (*nestedIt) <<" ";
}
putchar('\n');
}
}
int main(int argc, char const *argv[])
{
vector_Nested();
return 0;
}