foreach用法 C++
时间: 2023-10-19 11:30:45 浏览: 193
在C++中,可以使用std::for_each算法来对容器中的每个元素执行给定的函数。和C#或Java中的foreach用法类似,C++的foreach用法也非常方便。以下是两种常见的foreach用法示例:
引用中的示例演示了如何使用并行std::for_each遍历std::vector容器,并为每个元素加1:
```
#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::for_each(std::execution::par, numbers.begin(), numbers.end(), [](int& value) {
value += 1;
});
for (int number : numbers) {
std::cout << number << " ";
}
return 0;
}
```
引用中的示例展示了在C++中使用foreach的另一种用法:
```
#include <iostream>
#include <vector>
int main() {
int nums = {0, 1, 2};
std::vector<int> vs = {0, 1, 2, 3, 4};
for (int num : nums) {
std::cout << num << "\t";
}
std::cout << std::endl;
for (int v : vs) {
std::cout << v << "\t";
}
std::cout << std::endl;
for each (int num in nums) {
std::cout << num << "\t";
}
std::cout << std::endl;
for each (int v in vs) {
std::cout << v << "\t";
}
return 0;
}
```
需要注意的是,第一个示例是使用C++标准库中的std::for_each算法来遍历容器,而第二个示例是使用C++/CLI中的foreach语法来遍历数组和容器。两者虽然类似,但是使用的语法略有不同,所以需要注意区分。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [c++中的 for_each 函数](https://blog.csdn.net/weixin_43165135/article/details/125526408)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [c++你不知道的用法之foreach篇](https://blog.csdn.net/qq_21400315/article/details/50561030)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文