C++20 提供了一种新的遍历方式,即使用 'range-for循环' 结合 'std::views::enumerate' 视图来实现遍历时获取索引。

下面是一个简单的例子:

#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> vec{1, 2, 3, 4, 5};
    for (auto [index, value] : std::views::enumerate(vec)) {
        std::cout << "Index: " << index << ", Value: " << value << std::endl;
    }
    return 0;
}

输出结果为:

Index: 0, Value: 1
Index: 1, Value: 2
Index: 2, Value: 3
Index: 3, Value: 4
Index: 4, Value: 5

可以看到,使用 std::views::enumerate 视图,我们可以在遍历时同时获取索引和值。需要注意的是,这里使用了 C++17 中的结构化绑定语法,将索引和值分别绑定到了 'index' 和 'value' 变量上。

另外,需要在程序中包含 头文件,以使用 std::views::enumerate 视图。

C++20 遍历并获取索引:使用 std::views::enumerate

原文地址: https://www.cveoy.top/t/topic/lEYh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录