C++ Vector遍歷的幾種方式()

HW140701發表於2017-12-18
#include <vector>
#include <iostream>

using namespace std;

struct Point
{
	double x;
	double y;
	Point()
	{
		x = 0;
		y = 0;
	}
};


int main()
{
	vector<Point> m_testPoint;
	m_testPoint.clear();
	m_testPoint.shrink_to_fit();

	for (int i = 0; i<10; ++i)
	{
		Point temp;
		temp.x = i*i;
		temp.y = i*i;
		m_testPoint.push_back(temp);
	}

	//第一種遍歷方式,下標
	cout << "第一種遍歷方式,下標訪問" << endl;
	for (int i = 0; i<m_testPoint.size(); ++i)
	{

		cout << m_testPoint[i].x << "	" << m_testPoint[i].y << endl;
	}

	//第二種遍歷方式,迭代器
	cout << "第二種遍歷方式,迭代器訪問" << endl;
	for (vector<Point>::iterator iter = m_testPoint.begin(); iter != m_testPoint.end(); iter++)
	{
		cout << (*iter).x << "	" << (*iter).y << endl;
	}

	//第三種遍歷方式,auto關鍵字
	cout << "C++11,第三種遍歷方式,auto關鍵字" << endl;
	for (auto iter = m_testPoint.begin(); iter != m_testPoint.end(); iter++)
	{
		cout << (*iter).x << "	" << (*iter).y << endl;
	}

	//第四種遍歷方式,auto關鍵字的另一種方式
	cout << "C++11,第四種遍歷方式,auto關鍵字" << endl;
	for (auto i : m_testPoint)
	{
		cout << i.x << "	" << i.y << endl;
	}

	return 0;
}

相關文章