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

 C++使用如下方法遍历一个容器:

#include "stdafx.h"
#include<iostream>
#include<vector>

int main()
{
    std::vector<int> arr;
    arr.push_back(1);
    arr.push_back(2);

    for (auto it = arr.begin(); it != arr.end(); it++)
    {
        std::cout << *it << std::endl;
    }

    return 0;
}

其中auto用到了C++11的类型推导。同时我们也可以使用std::for_each完成同样的功能:

#include "stdafx.h"
#include<algorithm>
#include<iostream>
#include<vector>

void func(int n)
{
    std::cout << n << std::endl;
}

int main()
{
   
### 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&` 访问到实际存储于容器中的可变值,并对其进行更改。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值