STL 中的容器 算法 迭代器
1. 头文件
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
基本用法
void test1(){
vector<int> v;
v.push_back(1);
v.push_back(5);
v.push_back(3);
v.push_back(7);
vector<int>::iterator pStart = v.begin();
vector<int>::iterator pEnd = v.end();
while (pStart != pEnd){
cout << *pStart << " ";
pStart++;
}
cout << endl;
int n = count(pStart, pEnd, 5);
cout << "n:" << n << endl;
}
class Teacher
{
public:
Teacher(int age) :age(age){};
~Teacher(){};
public:
int age;
};
存储 Teacher 类型
void test2(){
vector<Teacher> v;
Teacher t1(10), t2(20), t3(30);
v.push_back(t1);
v.push_back(t2);
v.push_back(t3);
vector<Teacher>::iterator pStart = v.begin();
vector<Teacher>::iterator pEnd = v.end();
while (pStart != pEnd){
cout << pStart->age << " ";
pStart++;
}
cout << endl;
}
存储 Teacher 类型指针
void test3(){
vector<Teacher*> v;
Teacher* t1 = new Teacher(10);
Teacher* t2 = new Teacher(20);
Teacher* t3 = new Teacher(30);
v.push_back(t1);
v.push_back(t2);
v.push_back(t3);
vector<Teacher*>::iterator pStart = v.begin();
vector<Teacher*>::iterator pEnd = v.end();
while (pStart != pEnd){
cout << (*pStart)->age << " ";
pStart++;
}
cout << endl;
}
容器嵌套容器 难点
void test4()
{
vector< vector<int> > v;
vector<int>v1;
vector<int>v2;
vector<int>v3;
for (int i = 0; i < 5;i++)
{
v1.push_back(i);
v2.push_back(i * 10);
v3.push_back(i * 100);
}
v.push_back(v1);
v.push_back(v2);
v.push_back(v3);
for (vector< vector<int> >::iterator it = v.begin(); it != v.end();it++)
{
for (vector<int>::iterator subIt = (*it).begin(); subIt != (*it).end(); subIt ++)
{
cout << *subIt << " ";
}
cout << endl;
}
}
主函数main
int main(){
test4();
system("pause");
return EXIT_SUCCESS;
}