c++

如何在c++中使用visit遍历容器

小樊
81
2024-09-16 13:33:41
栏目: 编程语言

在C++中,std::visit 是一个函数,用于在 std::variant 或其他可访问类型的变体中访问其值

首先,需要包头文件。然后,创建一个std::variant 类型的容器(例如,std::vector<std::variant<…>>)。接下来,使用范围for循环遍历容器,并在每个元素上调用 std::visit`。

以下是一个示例:

#include<iostream>
#include<vector>
#include<variant>

int main() {
    // 定义一个包含 int 和 std::string 类型的 variant 容器
    std::vector<std::variant<int, std::string>> container = {10, "Hello", 20, "World"};

    // 使用 std::visit 遍历容器并处理每个元素
    for (const auto& elem : container) {
        std::visit([](const auto& value) {
            // 对于 int 类型的值
            if constexpr (std::is_same_v<decltype(value), int>) {
                std::cout << "Integer: "<< value<< std::endl;
            }
            // 对于 std::string 类型的值
            else if constexpr (std::is_same_v<decltype(value), std::string>) {
                std::cout << "String: "<< value<< std::endl;
            }
        }, elem);
    }

    return 0;
}

这将输出:

Integer: 10
String: Hello
Integer: 20
String: World

在此示例中,我们使用了 std::visit 来访问 std::variant 容器中的每个元素。对于每种类型,我们都有一个单独的处理分支。注意,我们使用了 if constexprstd::is_same_v 来检查当前值的类型。这样,编译器可以在编译时优化代码,并确保我们不会在运行时进行不必要的类型检查。

0
看了该问题的人还看了