C++11 之for循环的新用法

基本用法

#include <iostream>
using namespace std;

int main()
{
    //随机定义的数组
    int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };

    for (int i = 0; i < 10; i++) {
	    cout << array[i] << " ";		//输出:54 23 78 9 15 18 63 33 87 66

    return 0;
}

在C++11中,我们可以在for循环中填加冒号:来简化这个过程

1、拷贝range的元素时,使用for(auto x : range).

2、修改range的元素时,使用for(auto && x : range).

3、只读range的元素时,使用for(const auto & x : range).

举例说明:

#include <iostream>
using namespace std;

int main()
{
    //随机定义的数组
    int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };

    for (auto a : array) {
	    cout << a << " ";		//输出:54 23 78 9 15 18 63 33 87 66

    return 0;
}

注意:如果传入的迭代参数类型为非引用时,做的是值拷贝,因此修改数据是无效的。

#include<iostream>
using namespace std;

int main() {
	//随机定义的数组
	int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };

	for (auto a : array) {
		cout << a << " ";		//输出:54 23 78 9 15 18 63 33 87 66
	}

	cout << endl;
	for (auto a : array) {
		a++;					//改变后原数组中的数值不变
	}

	for (auto a : array) {
		cout << a << " ";		//输出:54 23 78 9 15 18 63 33 87 66(数值不变)
	}
	system("pause");
	return 0;
}

但是,如果传递的是引用,则可以改变原数组的值。

#include<iostream>
using namespace std;

int main() {
	//随机定义的数组
	int array[10] = { 54, 23, 78, 9, 15, 18, 63, 33, 87, 66 };

	for (auto a : array) {
		cout << a << " ";		//输出:54 23 78 9 15 18 63 33 87 66
	}

	cout << endl;
	for (auto &a : array) {		//传递了引用,因此改变数组中的值会有效果
		a++;
	}

	for (auto a : array) {
		cout << a << " ";		//输出:55 24 79 10 16 19 64 34 88 67(数值+1)
	}
	system("pause");
	return 0;
}

 基本遍历数组和容器

#include <iostream>
#include <vector>
using namespace std;
int main() {
    char arc[] = "http://c.biancheng.net/cplus/11/";
    //for循环遍历普通数组
    for (char ch : arc) {
        cout << ch;
    }
    cout << '!' << endl;
    vector<char>myvector(arc, arc + 23);
    //for循环遍历 vector 容器
    for (auto ch : myvector) {
        cout << ch;
    }
    cout << '!';
    return 0;
}

用 C++ 11 标准中的 for 循环遍历实例一定义的 arc 数组和 myvector 容器

#include <iostream>
#include <vector>
using namespace std;
int main() {
    char arc[] = "http://c.biancheng.net/cplus/11/";
    //for循环遍历普通数组
    for (char ch : arc) {
        cout << ch;
    }
    cout << '!' << endl;
    vector<char>myvector(arc, arc + 23);
    //for循环遍历 vector 容器
    for (auto ch : myvector) {
        cout << ch;
    }
    cout << '!';
    return 0;
}

新语法格式的 for 循环还支持遍历用{ }大括号初始化的列表

#include <iostream>
using namespace std;
int main() {
    for (int num : {1, 2, 3, 4, 5}) {
        cout << num << " ";
    }
    return 0;
}

另外值得一提的是,在使用新语法格式的 for 循环遍历某个序列时,如果需要遍历的同时修改序列中元素的值,实现方案是在 declaration 参数处定义引用形式的变量。举个例子:

#include <iostream>
#include <vector>
using namespace std;
int main() {
    char arc[] = "abcde";
    vector<char>myvector(arc, arc + 5);
    //for循环遍历并修改容器中各个字符的值
    for (auto &ch : myvector) {
        ch++;
    }
    //for循环遍历输出容器中各个字符
    for (auto ch : myvector) {
        cout << ch;
    }
    return 0;
}

C++11 for循环使用注意事项

  1. 首先需要明确的一点是,当使用 for 循环遍历某个序列时,无论该序列是普通数组、容器还是用{ }大括号包裹的初始化列表,遍历序列的变量都表示的是当前序列中的各个元素。

举个例子:

#include <iostream>
#include <vector>
using namespace std;
int main() {
    //for循环遍历初始化列表
    for (int ch : {1,2,3,4,5}) {
        cout << ch;
    }
    cout << endl;
    //for循环遍历普通数组
    char arc[] = "http://c.biancheng.net/cplus/11/";
    for (char ch : arc) {
        cout << ch;
    }
    cout << endl;
    //for循环遍历 vector 容器
    vector<char>myvector(arc, arc + 23);
    for (auto ch : myvector) {
        cout << ch;
    }
    return 0;
}

### C++ 中 `for` 循环结合 `auto` 关键字的使用 #### 使用 `auto` 和范围 `for` 循环遍历容器 当使用 `auto` 关键字与范围 `for` 循环(range-based for loop)结合时,可以显著简化遍历标准库容器(如 `std::vector`、`std::list` 等)的代码[^1]。 ```cpp #include <iostream> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; // 遍历并打印 vector 中的每一个元素 for (const auto& elem : vec) { std::cout << elem << std::endl; } return 0; } ``` 在这个例子中,`auto` 被用来自动推导迭代变量 `elem` 的类型。由于在声明时加上了引用符 `&`,因此 `elem` 是一个对 `vec` 容器内元素类型的常量引用 (`const int&`)。这不仅提高了性能(避免复制),还防止意外修改原始数据。 #### 处理不同类型的容器成员 对于包含复杂对象或大型结构体的数据结构来说,利用 `auto` 可以减少冗余代码的同时保持清晰度: ```cpp #include <iostream> #include <map> #include <utility> // For std::pair int main() { std::map<std::string, double> priceList{ {"apple", 0.79}, {"banana", 0.59}, {"orange", 0.89} }; // 这里我们获取的是 map 对象 key-value pair 类型的一个 const 引用 for (const auto& item : priceList) { std::cout << "The price of " << item.first << " is $" << item.second << ".\n"; } return 0; } ``` 这段程序展示了如何通过 `auto` 来处理更复杂的容器——在这里是一个关联数组 `std::map`。注意这里的 `item` 实际上是对 `std::pair<const string&,double>` 类型的对象的引用。 #### 修改容器内的元素 如果希望能够在范围内改变容器的内容,则应去掉 `const` 并保留引用操作符 `&`: ```cpp #include <iostream> #include <vector> void incrementElements(std::vector<int>& numbers){ for (auto& num : numbers) { ++num; // 原地增加每个数字 } } int main(){ std::vector<int> nums{1, 2, 3}; incrementElements(nums); for(int n : nums){ std::cout<<n<<" "; } return 0; } ``` 此片段说明了不带 `const` 的情况下,可以通过 `auto&` 访问到实际存储于容器中的可变值,并对其进行更改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值