Home > Back-end >  How to access members inside vector of structure
How to access members inside vector of structure

Time:12-16

I have a member variable which is of type vector of structure and which is defined as std::optional, so how do I access members inside the structure.

Example:

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

struct demoStruct
{
int a;
float b;
};

So how do i access 'a' and 'b' using mem_variable;

CodePudding user response:

You need to check if it contains the optional value and then you can dereference it.

Example:

#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';
        }
    }
}

Output:

1,2
3,4

CodePudding user response:

I think this may be helpful, I added a instance to the vector and printed one value, although I'm not sure you are properly using 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;
}

Note that in the cpp referenec page it's written that operator-> and operator* accesses the contained value

  • Related