《C++ Primer》學習記錄(1) 使用指針遍歷多維數組的三種方式

C++11標準引入兩個名爲begin/end的函數,這兩個函數與容器中的兩個同名成員功能類似,不過數組畢竟不是類類型,因此這兩個函數數不是數組的成員函數。故採用begin(a)、end(a)這樣的方式得到a的首元素指針、尾後指針。

請記住:指針也是迭代器!迭代器內部實現是智能指針(STL 源碼剖析)。

指向數組元素的指針擁有更多的功能,vector,string的迭代器支持的運算,數組的指針全部支持。
例如:像使用迭代器遍歷vector對象中元素一樣,使用指針也可以遍歷數組元素。
前提:獲取指向數組的第一個元素的指針+指向數組尾元素的下一位置指針(尾後指針)。
獲取數組指向首元素的指針:通過數組對象(數組名字)或數組首元素地址即可得到。
獲取數組指向尾元素的指針(尾後指針):使用下標運算符索引數組微元素下一位置的指針。

注意:
尾後指針項尾後迭代器一樣,不指向具體的元素,不能對尾後指針執行解引用或遞增操作。
尾後指針一目的:提供地址用於初始化“尾後迭代器”。

1、使用指針遍歷一維數組的三種方式

void test5()
{
	constexpr int size = 10;
	int a[size] = { 0,10,20,30,40,50,60,70,80,90 };
	cout << "for (int *pbeg = a; pbeg != pe; ++pbeg)" << endl;
	int *pe = a + size;//等價於 int *pe = &a[size];
	for (int *pbeg = a; pbeg != pe; ++pbeg)
	{
		cout << *pbeg << "\t";
	}
	cout << endl;

	//1、指針也是迭代器
	cout << "for (int *b = a; b != &a[size]; ++b)" << endl;
	for (int *pbeg = a; pbeg != &a[size]; ++pbeg)
	{
		cout << *pbeg << "\t";
	}
	cout << endl;

	//2、C++11標準引入兩個名爲begin\end的函數
	int *pbeg = begin(a);
	int *pend = end(a);
	cout << "int *pbeg = begin(a);int *pend = end(a);while (pbeg != pend)" << endl;
	while (pbeg != pend)
	{
		cout << *pbeg << "\t";
		++pbeg;
	}
	cout << endl;
}

在這裏插入圖片描述
2、使用指針遍歷多維數組的三種方式

void test9()
{
	//使用指針遍歷多維數組
	constexpr int row = 3;
	constexpr int col = 4;
	int a[row][col] = { { 0,10,20,30 },{ 40,50,60,70 },{ 80,90,100,110 } };
	cout << "==================================1st way" << endl;
	cout << "for (auto p = a; p != a + row; ++p)" << endl;
	cout << "	for (auto q = *p; q != *p + col; ++q)" << endl;
	for (auto p = a; p != a + row; ++p)
	{
		for (auto q = *p; q != *p + col; ++q)
		{
			cout << *q << "\t";
		}
		cout << endl;
	}
	cout << endl << endl;

	cout << "==================================2ed way" << endl;
	cout << "for (auto p = begin(a); p != end(a); ++p)" << endl;
	cout << "	for (auto q = begin(*p); q != end(*p); ++q)" << endl;
	for (auto p = begin(a); p != end(a); ++p)
	{
		for (auto q = begin(*p); q != end(*p); ++q)
		{
			cout << *q << "\t";
		}
		cout << endl;
	}
	cout << endl << endl;


	cout << "==================================3rd way" << endl;
	cout << "using int_arr = int[4];" << endl;
	cout << "for (int_arr *p = a; p != a + row; ++p)" << endl;
	cout << "	for (int *q = *p; q != *p + 4; ++q)" << endl;
	using int_arr = int[4];//C++11標準下類型別名的聲明
						   //typedef int int_arr[4];//等價的typedef聲明
	for (int_arr *p = a; p != a + row; ++p)
	{
		for (int *q = *p; q != *p + 4; ++q)
		{
			cout << *q << "\t";
		}
		cout << endl;
	}
	cout << endl;
}

在這裏插入圖片描述
《C++ Primer》學習記錄(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章