01 STL初识–vector存放内置数据类型
#include<iostream>
using namespace std;
#include<vector>
#include <algorithm> //标准算法的头文件
/*
容器:vector
算法:for_each
迭代器:vector<int>::iterator
*/
void MyPrint(int val)
{
cout << val << endl;
}
void test01()
{
//创建一个vector容器
//创建vector容器对象,并且通过模板参数指定容器存放的数据类型
vector<int>v;
//向容器中插入数据
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
v.push_back(50);
/*
每一个容器都有自己的迭代器,迭代器是用来遍历容器中的元素的
vector<int>::iterator 拿到vector<int>这种容器的迭代器
*/
vector<int>::iterator pBegin = v.begin();
vector<int>::iterator pEnd = v.end(); //返回迭代器 指向容器元素的最后一个元素的下一个位置
//第一种遍历方式
while (pBegin != pEnd)
{
cout << *pBegin << endl;
pBegin++;
}
//第二种方式
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << endl;
}
//第三种
for_each(v.begin(), v.end(), MyPrint);
}
int main()
{
test01();
return 0;
}
02 STL 初识-vector存放自定义数据类型
#include<iostream>
using namespace std;
#include<string>
#include<vector>
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->m_Age = age;
}
string m_Name;
int m_Age;
};
//void test01()
//{
// vector<Person>v;
//
// Person p1("a", 1);
// Person p2("a", 2);
// Person p3("a", 3);
// Person p4("a", 4);
// Person p5("a", 5);
//
// v.push_back(p1);
// v.push_back(p2);
// v.push_back(p3);
// v.push_back(p4);
// v.push_back(p5);
//
// for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
// {
// cout << "姓名: " << (*it).m_Name << "年龄:" << (*it).m_Age << endl;
// }
//
//}
void test02()
{
vector<Person* >v;
Person p1("a", 1);
Person p2("a", 2);
Person p3("a", 3);
Person p4("a", 4);
Person p5("a", 5);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
v.push_back(&p5);
for (vector<Person*>::iterator it = v.begin(); it != v.end(); it++)
{
Person* p = (*it);
cout << "姓名: " << (*it)->m_Name << "年龄:" << (*it)->m_Age << endl;
}
}
int main()
{
test02();
return 0;
}
03 STL 初识 _容器嵌套容器
#include<iostream>
using namespace std;
#include <vector>
void test01()
{
vector<vector<int>>v;
//创建小容器
vector<int>v1;
vector<int>v2;
vector<int>v3;
vector<int>v4;
vector<int>v5;
//向小容器添加数据
for (int i = 0; i < 4; i++)
{
v1.push_back(i + 1);
v2.push_back(i + 2);
v3.push_back(i + 3);
v4.push_back(i + 4);
}
//将小容器插入到大容器中
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
v.push_back(v4);
//通过大容器,把所有数据遍历一遍
for (vector<vector<int>>::iterator it = v.begin(); it != v.end(); it++)
{
//(*it)--容器 vector<int>
for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++)
{
cout << *vit << " ";
}
cout << endl;
}
}
int main()
{
test01();
return 0;
}