c++ 范围循环
时间: 2023-08-04 07:19:16 浏览: 41
C++11 引入了范围循环(range-based for loop)语法,它可以方便地遍历一个序列或容器中的元素,如下所示:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
// 使用范围循环遍历 vector 中的元素
for (int x : vec) {
std::cout << x << " ";
}
return 0;
}
```
输出结果为:`1 2 3 4 5`。
在范围循环中,可以使用 `auto` 关键字自动推导类型,也可以使用引用类型避免元素的拷贝:
```cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec{1, 2, 3, 4, 5};
// 使用引用类型避免元素的拷贝
for (int& x : vec) {
x *= 2;
}
// 使用 auto 关键字
for (auto x : vec) {
std::cout << x << " ";
}
return 0;
}
```
输出结果为:`2 4 6 8 10`。
相关问题
c++ for循环题目
以下是一个C++的for循环题目的示例代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int k = (1 + i) * i / 2;
cout << k << endl;
}
return 0;
}
```
这段代码的功能是计算从1到n的所有整数的累加和,并将结果逐行输出。其中,变量n是用户输入的一个整数,表示累加的范围。
c++ 增强for循环
C++中没有像Java或Python中的增强for循环(foreach循环)那样的语法结构。但是,你可以使用范围-based for循环来达到类似的效果。
范围-based for循环是C++11引入的一种循环结构,用于遍历容器(如数组、向量、列表等)中的元素。它的语法形式如下:
```cpp
for (element_type element : container) {
// 循环体
}
```
其中,`element_type`是容器中元素的类型,`element`是循环变量,`container`是要遍历的容器。
下面是一个使用范围-based for循环遍历数组的示例:
```cpp
int arr[] = {1, 2, 3, 4, 5};
for (int num : arr) {
cout << num << " ";
}
// 输出结果:1 2 3 4 5
```
在每次循环迭代中,`num`会依次取到数组`arr`中的每个元素,并执行循环体内的操作。
需要注意的是,范围-based for循环只适用于遍历容器中的元素,并不能修改容器中的元素。如果需要修改容器中的元素,可以使用传统的for循环。