【问题标题】:如何访问结构向量内的成员
【发布时间】:2022-01-19 10:16:49
【问题描述】:

我有一个成员变量,它是结构向量类型,定义为 std::optional,那么我如何访问结构内的成员。

例子:

std::optional<std::vector<demoStruct>> mem_variable;

struct demoStruct
{
int a;
float b;
};

那么我如何使用 mem_variable 访问“a”和“b”;

【问题讨论】:

  • 首先您必须确保mem_variable 确实有一个值(毕竟它 可选的)。然后你必须弄清楚你想要哪个向量元素。然后像任何其他结构一样打印该元素的值。
  • 请注意,在您的代码中,vector 是可选的,而不是矢量内的值。这通常是没有意义的。也许你想要一个可选值的向量(比如std::vector&lt;std::optional&lt;demoStruct&gt;&gt;)?
  • 你知道如何访问optional 中的值吗?你知道如何访问vector 的元素吗?您在文档中没有找到哪个部分?你有没有尝试过?

标签: c++ struct stdvector stdoptional


【解决方案1】:

你需要检查它是否包含可选值,然后你可以取消引用它。

例子:

#include <iostream>
#include <optional>
#include <vector>

struct demoStruct {
    int a;
    float b;
};

int main() {
    std::vector<demoStruct> foo{{1,2.f}, {3,4.f}};

    std::optional<std::vector<demoStruct>> mem_variable = foo;

    if(mem_variable) { // check that it contains a vector<demoStruct>

        // dereference the optional to get the stored value
        std::vector<demoStruct>& value_ref = *mem_variable;

        // display the contents of the vector
        for(demoStruct& ds : value_ref) {
            std::cout << ds.a << ',' << ds.b << '\n';
        }
    }
}

输出:

1,2
3,4

【讨论】:

    【解决方案2】:

    我认为这可能会有所帮助,我在向量中添加了一个实例并打印了一个值,尽管我不确定您是否正确使用 optional

    #include <iostream>
    #include <vector>
    #include <optional>
    
    struct demoStruct
    {
    int a;
    float b;
    };
    
    int main()
    {
        //Create an instance
        demoStruct  example;
        example.a = 42;
        example.b = 43.0;
    
        std::optional<std::vector<demoStruct>> mem_variable;
        //Add created instance to vector
        mem_variable->push_back(example);
        std::cout << mem_variable->at(0).a; // prints 42
    
    
        return 0;
    }
    

    请注意,在cpp referenec page 中写到operator-&gt;operator* 访问包含的值

    【讨论】:

      猜你喜欢
      • 2018-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      相关资源
      最近更新 更多