- STL(Standard Template Library,标准模板库)
- 广义上分为:容器(container),算法(algorithm),迭代器(iterator)。容器和算法之间通过迭代器进行连接。
- STL中几乎所有代码均采用了类模板或者函数模板
STL中容器、算法、迭代器
Vector容器
#include <vector>
#include <algorithm> //标准算法头文件
using namespace std;
void kPrint(int i)
{
cout << i << endl;
}
int main()
{
vector<int> v;
v.push_back(0); //push_back尾插法为容器插入数据
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
//需求:遍历打印
//1. for循环打印
for (vector<int>::iterator itbegin = v.begin(); itbegin != v.end(); ++itbegin)
{
cout << *itbegin << endl;
}
//2. while循环打印
vector<int>::iterator itbegin = v.begin();//起始迭代器,指向容器中第一个元素的位置
vector<int>::iterator itend = v.end();//结束迭代器,指向容器中最后一个元素的下一个位置
while (itbegin != itend)
{
cout << *itbegin << endl;
++itbegin;
}
//3. for_each算法遍历
vector<int>::iterator itbegin = v.begin();//起始迭代器,指向容器中第一个元素的位置
vector<int>::iterator itend = v.end();//结束迭代器,指向容器中最后一个元素的下一个位置
for_each(itbegin, itend, kPrint);
system("pause");
return 0;
}
vector存放自定义数据类型
#include "test1.h"
#include "iostream"
#include "string"
#include <vector>
#include <algorithm> //标准算法头文件
using namespace std;
class Person
{
public:
Person(string name, int age)
{
this->m_name = name;
this->m_age = age;
}
string m_name;
int m_age;
};
void test01()
{
Person p1("Tom", 8);
Person p2("Jerry", 10);
Person p3("Katty", 9);
Person p4("Sophia", 5);
vector<Person> p;
p.push_back(p1);
p.push_back(p2);
p.push_back(p3);
p.push_back(p4);
for (vector<Person>::iterator i = p.begin(); i!=p.end(); i++)
{
cout << "name: " << i->m_name << " age: " << i->m_age << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}
容器嵌套容器
vector<int> v1;
vector<int> v2;
vector<int> v3;
for (int i = 0; i<3; ++i)
{
v1.push_back(i);
v2.push_back(i * i);
v3.push_back(i * i *i);
}
vector<vector<int>> v;
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
for (vector<vector<int>>::iterator vi = v.begin(); vi != v.end(); vi++)
{
for (vector<int>::iterator vti = (*vi).begin(); vti != (*vi).end(); vti++)
{
cout << *vti << " ";
}
cout << endl;
}