001vector容器初识定义和3种遍历

#include<iostream>
#include <vector>
#include <algorithm>

using namespace std;
void MyPrint(int val)
{
	cout << "---------------------------3--";
	cout << val << endl;
}
void test()
{
	//创建vector容器对象,并且通过模板参数指定容器中存放的数据类型
	vector<int> v1;
	//通过尾插法向容器中存储数据
	v1.push_back(100);
	v1.push_back(200);
	v1.push_back(300);
	v1.push_back(400);

	//每一个容器都有自己的迭代器,迭代器是用来遍历容器中的元素
	//v.begin()返回迭代器,这个迭代器指向容器中第一个数据
	//v.end()返回迭代器,这个迭代器指向容器元素的最后一个元素的下一个
	//vector<int>::iterator 拿到vector<int>这种容器的迭代器类型

	vector<int>::iterator pBegin = v1.begin();//可以当作一个指针使用
	vector<int>::iterator pEnd = v1.end();
	//	typedef typename _Mybase::iterator iterator;//关于上面定义vector<int>::可以当作域修饰符号

	//第一种遍历方式
	while (pBegin!=pEnd)
	{
		cout << "------------------------------1--";
		cout << *pBegin << endl;
		pBegin++;
	}

	//第二种遍历方式
	for (vector<int>::iterator it = v1.begin(); it != v1.end();it++)
	{
		cout << "------------------------------2--";
		cout << *it << endl;
	}

	//第三种使用stl提供的标准遍历算法 使用for_each
	for_each(v1.begin(), v1.end(), MyPrint);//这里只需要写上函数名字即可


}

int main(void)
{
	test();

	system("pause");
	return 0;
}
/*
 * ------------------------------1--100
------------------------------1--200
------------------------------1--300
------------------------------1--400
------------------------------2--100
------------------------------2--200
------------------------------2--300
------------------------------2--400
---------------------------3--100
---------------------------3--200
---------------------------3--300
---------------------------3--400
请按任意键继续. . .
 */

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89513563