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)