0
点赞
收藏
分享

微信扫一扫

C++ ranged-base for

C++ ranged-base for_迭代

在C++中,基于范围的for循环(通常称为for each循环)通过C++11标准引入,它提供了一种更简洁和安全的方式来遍历容器(如数组、向量、列表等)中的所有元素。基于范围的for循环会自动迭代容器的每个元素,无需手动操作迭代器或者索引。

基于范围的for循环的基本语法如下:

for (declaration : container) {
    // 使用当前元素
}

declaration 是对容器中元素的引用,而container是要迭代的容器。下面是一些C++基于范围的for循环使用的例子:

遍历std:vector 容器

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    
    for (int element : v) {
        std::cout << element << " ";
    }
    
    return 0;
}

如果想要在循环中更改容器的元素,则需要使用引用类型,如下:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    
    for (int& element : v) {
        element *= 2; // Double each element
    }

    for (const int element : v) { // "const" here is optional as we are not modifying the elements
        std::cout << element << " ";
    }
    
    return 0;
}

举报

相关推荐

0 条评论