一. 基于范围的for循环简介
在C++03/98中,不同的容器和数组,遍历的方法不尽相同,写法不统一,也不够简洁,而C++11基于范围的for循环以统一,简洁的方式来遍历容器和数组,用起来更方便了。
数组循环:
using namespace std;
const int size = 5;
int* p = new int[size]{1,2,3,4,5};
for(int i =0;i<size;i++){
cout<<p[i]<<" ";
}
容器循环:
using namespace std;
vector<int> vec;
for (auto it=vec.begin(),it!=vec.end();it++){
cout<<*it<<" ";
}
当然,<algorithm>中还有一个for_each算法可以用来对容器进行遍历
Function for_each( InputIterator begin, InputIterator end, Function f ) {
while ( begin != end )
f( *begin++ );
}
using namespace std;
void do_cout(int& num){
cout<<num<<" ";
}
vector<int> vec;
for_each(vec.begin(),vec.end(),do_cout);
for_each
优点:不再需要关注迭代器(Iterator)的概念
缺点:必须显示的给出容器的开头(Begin)和结尾(End)
在C++11中终于有基于范围的for循环(The range-based for statement)。
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> arr = {1, 2, 3};
for(auto n : arr){
cout << n << endl;
}
return 0;
}
在上面的基于范围的for循环中,在n的定义之后,紧跟一个冒号(:),之后直接写上需要遍历的表达式,

C++11引入了基于范围的for循环,提供了一种统一、简洁的方式来遍历容器和数组。它简化了遍历过程,避免了显式使用迭代器。在循环中,可以通过引用修改容器内的值,但对于某些只读容器,如std::set,内部元素可能是const的。此外,范围for循环的开始和结束表达式只在循环开始前执行一次。自定义类型要支持范围for循环,需要提供begin和end成员函数或友元函数。
最低0.47元/天 解锁文章
1468

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



