//win10下,VS2017中编译
#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;
int main()
{
int a[] = { 2,3,5,7 };//整型数组
vector<int> v = { 6,8,5,1,7 };//vector容器,直接初始化
//方式一,下标
for (int i = 0; i < 4; ++i)
{
cout << a[i] << "\t";
}
cout << endl;
for (int i = 0; i < v.size(); ++i)
{
cout << v[i] << "\t";
}
cout << endl;
//方式二,迭代器,类似于指针
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << *it << "\t";
}
cout << endl;
//用auto改写,auto自动推导类型
/* for (auto i = 0; i < 4; ++i)
{
cout << a[i] << "\t";
}
cout << endl;
for (auto it = v.begin(); it != v.end(); ++it)
{
cout << *it << "\t";
}
cout << endl;
*/
//方式三,C++11/14引入 :(本质上是迭代器实现)
for (const auto& x : a)
{
cout << x << "\t";
}
cout << endl;
for (auto& x : v)
{
cout << x << "\t";
}
cout << endl;
//方式四,BOOST_FOREACH,不仅支持数组、容器,还支持迭代器的pair和逆序遍历
//#include "boost/foreach.hpp"
/* BOOST_FOREACH(auto& x, v)
{
cout << x << "\t";
}
*/
return 0;
}
几种类型的for循环
最新推荐文章于 2023-07-10 13:57:21 发布