range-based for循环

  C++11提供了一种基于范围的for循环,这对于STL迭代器的使用大为简化,语法如下——

#include
#include
using namespace std;

int main(){
	vector<int> v1 = {1,3,5,7,9};
	vector<int> v2 = {2,4,6,8,10};
	v1.insert(v1.end(),v2.begin(),v2.end());
	// range-based for
	for(auto elem:v1){
		cout<<elem<<endl;
	}
	// iterator for
	/*for(vector::iterator it = v1.begin();it!=v1.end();it++){
		cout<<*it<
	return 0;  
} 

range-based for循环_第1张图片

  这种方法能够带来与迭代器访问容器相同的效果,需要特别注意的是,这种方式是只读的,比如说,要使用这种方式修改元素,那就不行了——

#include
#include
using namespace std;

int main(){
	vector<int> v1 = {1,3,5,7,9};
	vector<int> v2 = {2,4,6,8,10};
	v1.insert(v1.end(),v2.begin(),v2.end());
	for(auto elem:v1){
		elem++;
	} 
	for(auto elem:v1){
		cout<<elem<<endl;
	}
	return 0;  
}

range-based for循环_第2张图片

  如果想对访问的容器进行读写,改为引用就可以了——

#include
#include
using namespace std;

int main(){
	vector<int> v1 = {1,3,5,7,9};
	vector<int> v2 = {2,4,6,8,10};
	v1.insert(v1.end(),v2.begin(),v2.end());
	// 加入引用
	for(auto&elem:v1){
		elem++;
	} 
	for(auto elem:v1){
		cout<<elem<<endl;
	}
	return 0;  
}

range-based for循环_第3张图片
  如我所愿,结果发生了相应的改动。emmm……之前忽略了这一特性,在刷PAT的时候有一处结果特别反常,翻来覆去找了将近一天,结果发现居然是这种低端错误……无语Orz~~~

你可能感兴趣的:(C/C++)