初识容器算法迭代器
1、 vector<类型> v 容器
2、 尾插 v.push_back
3、起始迭代器 v.begin() 指向第一个元素
4、结束迭代器 v.end() 指向容器最后一个元素下一个位置
5、for_each() 遍历, 引入头文件 algorithm
6、练习:内置类型、自定义类型、容器嵌套
#include <iostream>
#include <vector>
#include <algorithm> //系统算法头文件
#include <string>
using namespace std;
void myPrint(int val)
{
cout << val << endl;
}
//普通的指针也是一种迭代器
void test01()
{
int arr[5] = {1, 5, 2, 7, 3};
int *p = arr;
for(int i = 0; i < 5; i++)
{
cout << *(p++) << endl;
}
}
//内置属性类型
void test02()
{
vector<int> v; //声明一个vector容器
//向容器中添加数据
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
//通过迭代器可以遍历容器
//每个容器都有自己的专属迭代器
//第一种遍历方式
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << endl;
}
//第二种遍历方式,系统算法
for_each(v.begin(), v.end(), myPrint);
}
class Person
{
public:
Person(string name, int age)
{
this->myName = name;
this->myAge = age;
}
string myName;
int myAge;
};
//自定义类型
void test03()
{
vector<Person> v;
Person p1("a", 13);
Person p2("b", 14);
Person p3("c", 15);
Person p4("d", 16);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
for(vector<Person>::iterator it = v.begin(); it != v.end(); it ++)
{
//*it --- Person类型
cout << " 姓名: " << (*it).myName << " 年龄: " << it->myAge << endl;
}
}
void test04()
{
vector<Person*> v;
Person p1("a", 13);
Person p2("b", 14);
Person p3("c", 15);
Person p4("d", 16);
v.push_back(&p1);
v.push_back(&p2);
v.push_back(&p3);
v.push_back(&p4);
for(vector<Person*>::iterator it = v.begin(); it != v.end(); it ++)
{
//*it --- Person*类型
cout << " 姓名: " << (*it)->myName << " 年龄: " << (*it)->myAge << endl;
}
}
//容器嵌套
void test05()
{
vector< vector<int> > v ; //相当于一个二维数组
vector<int> v1;
vector<int> v2;
vector<int> v3;
vector<int> v4;
for (int i = 0; i < 10 ; i++)
{
v1.push_back(i+1);
v2.push_back(i+10);
v3.push_back(i+100);
v4.push_back(i+1000);
}
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 it2 = (*it).begin(); it2 != (*it).end(); it2++)
{
// (*it2) --- int
cout << *it2 ;
}
cout << endl;
}
}
int main()
{
//test01();
//test02();
//cout << "Hello world!" << endl;
//test03();
//test04();
test05();
return 0;
}