void main()
{
//遍历数组元素的方法
int a[] = { 1, 2, 3, 4, 5, 6, 7 };
cout << “第一种:\n”;
for (int i = 0; i < sizeof(a) / sizeof(a[0]);i++)
{
cout << a[i] << " ";
}
cout << endl;
cout << "第二种:\n";
int nsize = sizeof(a) / sizeof(a[0]);
for (int *p = a; p < a + sizeof(a) /sizeof( a[0]);p++)
{
cout << *p << " ";
}
cout << "\n";
cout << "--------------------\n";
//标准库函数begin和end
cout << “第三种使用begin,end:\n”;
for (int *p = begin(a); p != end(a);p++)
{
cout << *p << " ";
}
cout << "第三种使用a,end:\n";
for (int *p = a; p != end(a); p++)
{
cout << *p << " ";
}
vector<int> m_vc{1,2,3};
for (auto it = begin(m_vc); it != end(m_vc);it++)
{
cout << *it << endl;
}
system("pause");
}
结果:

本文介绍了使用C++遍历数组的三种不同方法,包括传统的for循环、指针迭代及利用标准库函数begin()和end()。此外还展示了如何用相同方法遍历vector容器。
1万+

被折叠的 条评论
为什么被折叠?



