C++11 范围 for

作用

遍历给定序列中的每个元素并对序列中的每个值执行某种操作。

语法

for (declaration : expression)
    statement

其中:

expression 部分是一个对象,用于表示一个序列;
declaration 部分负责定义一个变量,该变量被用于访问序列中的基础元素;
每次迭代,declaration 部分的变量会被初始化为 expression 部分的下一个元素值。

示例

不改变原值

例1. 使用范围 for 遍历 string

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str("hello");
    for (auto a : str)
    {
        cout << a << endl;
    }
    return 0;
}

〖注〗编译环境:[CentOS 7] 、 [g++ 4.8.5] 编译时需要添加 -std=c++11
输出结果:
在这里插入图片描述

例2. 使用范围 for 遍历 vector

#include <iostream>
#include <vector>
using namespace std;

int main()
{
	vector<int> vec;
	for (int i = 0; i < 5; ++i)
		vec.push_back(i);
	
	for (auto a : vec)                               // range for
	{
		cout << "range: " << a << endl;
	}

	vector<int>::iterator it;
	for (it = vec.begin(); it != vec.end(); ++it)    // iterator
	{
		cout << "iterator: " << *it << endl;
	}

	unsigned int size = vec.size();
	for (unsigned int i = 0; i < size; ++i)          // at
	{
		cout << "at: " << vec.at(i) << endl;
	}
	return 0;
}

输出结果
在这里插入图片描述

改变原值

上面两个例子是输出对象中的元素,若要使用范围 for 改变对象中元素的值,则必须把循环变量定义成引用类型。

例3. 使用 range for 改变 string 对象中的字符

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str("hello");
	for (auto & a : str)      // 引用
	{
		a = toupper(a);
	}
	cout << str << endl;
	
	return 0;
}

输出结果:
在这里插入图片描述

范围 for 的使用就是这样简单 ?

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值