01 STL初识-vector存放内置数据类型

02 STL初识-vector存放自定义数据类型

03 STl初始 容器嵌套容器


01 STL初识-vector存放内置数据类型

#include<iostream>
using namespace std;
#include <vector>
#include <algorithm> //标准算法头文件

void print(int val)
{
	cout << val << endl;
}
void test01()
{
	//创建一个vector容器,数组
	vector<int> v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);
	
	cout << "第一种遍历方式:while循环" << endl;
	//通过迭代器访问容器中的数据
	vector<int>::iterator itBegin = v.begin(); //起始迭代器,指向容器中第一个元素
	vector<int>::iterator itEnd = v.end(); //结束迭代器,指向容器中最好一个元素的下一个位置
	while (itBegin != itEnd)
	{
		cout << *itBegin << endl; //*取值
		itBegin++;
	}
	cout << "第二种遍历方式:for循环" << endl;
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << * it << endl;
	}
	cout << "第三种:利用STL提高遍历算法for_each,要加入头文件algorithm,输出要定义函数print" << endl;

	for_each(v.begin(), v.end(), print);
}

int main() {
	test01();
	system("pause");
	return 0;
}

02 STL初识-vector存放自定义数据类型

#include<iostream>
using namespace std;
#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> p;
	//创建数据
	Person p1("张三", 12);
	Person p2("张四", 16);
	Person p3("张五", 232);
	Person p4("张六", 342);
	Person p5("张七", 45);
	p.push_back(p1);
	p.push_back(p2);
	p.push_back(p3);
	p.push_back(p4);
	p.push_back(p5);
	for (vector<Person>::iterator it = p.begin(); it != p.end(); it++)
	{
		cout << "(解引用:Person数据类型)姓名:" << (*it).m_name << ",年龄:" << (*it).m_age << endl;
		cout << "(it指针->)姓名:" << it->m_name << ",年龄:" << it->m_age << endl;

	}

}

//存放自定义类型指针
void test02()
{
	vector<Person*> p;
	Person p1("张三", 12);
	Person p2("张四", 16);
	Person p3("张五", 232);
	Person p4("张六", 342);
	Person p5("张七", 45);
	//项容器中添加数据,取地址
	p.push_back(&p1);
	p.push_back(&p2);
	p.push_back(&p3);
	p.push_back(&p4);
	p.push_back(&p5);
	//遍历容器
	for (vector<Person*>::iterator it = p.begin(); it != p.end(); it++)
	{
		cout << "(Person*是指针(*it)用->):姓名:" << (*it)->m_name << ",年龄:" << (*it)->m_age << endl;

	}

}
int main() {
	test01();
	test02();
	system("pause");
	return 0;
}

03 STl初始 容器嵌套容器

#include<iostream>
using namespace std;
#include<vector>

//容器镶嵌容器
void test()
{
	vector<vector<int>> v;
	//创建小容器
	vector<int> v1;
	vector<int> v2;
	vector<int> v3;
	vector<int> v4;
	//向小容器添加数据
	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()
{
	test();
	system("pause");
	return 0;
}