C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ based for循环

C++中based for循环的实现

作者:花落已飘

C++中的范围for循环是一种简洁的遍历容器的方法,本文主要介绍了C++中based for循环的实现,具有一定的参考价值,感兴趣的可以了解一下

在 C++ 中,based for 循环并不是一种标准的语法,可能是你想询问的实际上是 范围基(range-based)for 循环。这种循环语法是在 C++11 中引入的,旨在简化遍历容器(如数组、std::vectorstd::map 等)的代码。

范围基 for 循环(Range-based for Loop)

范围基 for 循环用于遍历容器或数组中的所有元素,而不需要显式地使用索引或迭代器。它的语法非常简洁,适用于任何可以迭代的容器。

语法格式

for (declaration : container) {
    // 循环体
}

例子

1. 遍历数组

#include <iostream>

int main() {
    int arr[] = {1, 2, 3, 4, 5};

    // 使用范围基 for 循环遍历数组
    for (int num : arr) {
        std::cout << num << " ";
    }

    return 0;
}

输出:

1 2 3 4 5

在这个例子中,num 会依次获取数组中的每个元素,直到遍历完整个数组。

2. 遍历 std::vector

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {10, 20, 30, 40, 50};

    // 使用范围基 for 循环遍历 std::vector
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

输出:

10 20 30 40 50

3. 使用引用避免拷贝

如果容器中的元素是较大的对象,或者你不希望拷贝元素,使用引用来避免不必要的拷贝。

#include <iostream>
#include <vector>

class Person {
public:
    std::string name;
    Person(std::string n) : name(n) {}
};

int main() {
    std::vector<Person> people = {Person("Alice"), Person("Bob"), Person("Charlie")};

    // 使用引用避免拷贝
    for (Person& p : people) {
        std::cout << p.name << " ";
    }

    return 0;
}

输出:

Alice Bob Charlie

4. 使用常量引用

如果不需要修改容器中的元素,可以使用常量引用来提高效率(避免不必要的拷贝,并保护数据不被修改)。

#include <iostream>
#include <vector>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};

    // 使用常量引用,避免拷贝且不修改元素
    for (const int& num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

输出:

1 2 3 4 5

特殊用法

5. 遍历 std::map 或 std::unordered_map

对于 std::map 或 std::unordered_map,每个元素都是一个键值对,因此迭代时需要使用 auto 来推导类型。

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> m = {{1, "One"}, {2, "Two"}, {3, "Three"}};

    // 遍历 map(键值对)
    for (const auto& pair : m) {
        std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
    }

    return 0;
}

输出:

Key: 1, Value: One
Key: 2, Value: Two
Key: 3, Value: Three

总结

范围基 for 循环 是一种简洁、直观的方式来遍历容器,它:

使用范围基 for 循环,可以极大地提高代码的简洁性和可读性,尤其是在需要遍历容器时。

到此这篇关于C++中based for循环的实现的文章就介绍到这了,更多相关C++ based for循环内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文