大家好:
衷心希望各位点赞。
您的问题请留在评论区,我会及时回答。
vector存放基本数据类型
STL中最常用的容器就是vector,可以理解成为数组。
需要掌握如何向vector容器插入数据、遍历vector。
#include <iostream>
#include <Windows.h>
#include <vector>
#include <algorithm> // 使用STL提供的遍历算法,遍历vector容器
using namespace std;
void myPrint(int val)
{
cout << val << endl;
}
void test()
{
// 创建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 itBegin = v.begin(); // 起始迭代器:指向第一个元素
vector<int>::iterator itEnd = v.end(); // 结束迭代器:指向容器中最后一个元素的下一个位置
// 遍历容器
// 第一种遍历方式
while (itBegin != itEnd)
{
cout << *itBegin << endl;
itBegin++;
}
// 第二种遍历方式
for (vector<int>::iterator itBegin = v.begin(); itBegin != v.end(); itBegin++)
{
cout << *itBegin << endl;
}
// 第三种遍历方式:利用STL提供的遍历算法,包含头文件<algorithm>
for_each(v.begin(), v.end(), myPrint);
}
int main(void)
{
test();
system("pause");
return 0;
}
vector存放自定义的数据类型
#include <iostream>
#include <Windows.h>
#include <string>
#include <vector>
#include <algorithm> // 使用STL提供的遍历算法,遍历vector容器
using namespace std;
class Person
{
public:
string m_Name;
int m_Age;
Person(string name, int age)
{
m_Name = name;
m_Age = age;
}
};
void test()
{
// 创建vector容器
vector<Person> v;
Person p1("张三", 18);
Person p2("李四", 19);
Person p3("王五", 20);
Person p4("赵六", 21);
Person p5("田七", 22);
// 向vector容器插入数据
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
v.push_back(p5);
// 遍历vector容器
for (vector<Person>::iterator itBegin = v.begin(); itBegin != v.end(); itBegin++)
{
cout << "姓名:" << itBegin->m_Name << " 年龄:" << itBegin->m_Age << endl;
}
}
int main(void)
{
test();
system("pause");
return 0;
}
vector容器嵌套容器
容器中嵌套容器,相当于二维数组。
#include <iostream>
#include <Windows.h>
#include <string>
#include <vector>
#include <algorithm> // 使用STL提供的遍历算法,遍历vector容器
using namespace std;
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);
// 遍历大容器vector
for (vector<vector<int>>::iterator itBegin = v.begin(); itBegin != v.end(); itBegin++)
{
for (vector<int>::iterator vit = itBegin->begin(); vit != itBegin->end(); vit++)
{
cout << *vit << " ";
}
cout << endl;
}
}
int main(void)
{
test();
system("pause");
return 0;
}