-1

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;

  • 1
    First you have to make sure that `mem_variable` really have a value (it *is* optional after all). Then you have to figure out which of the vectors element you want. Then you print the values of that element like any other structure. – Some programmer dude Dec 16 '21 at 10:03
  • And note that in your code it's the *vector* that is optional, not the values inside the vector. That usually makes no sense. Perhaps you wanted a vector of optional values (like `std::vector>`)? – Some programmer dude Dec 16 '21 at 10:04
  • do you know how to access the value in an `optional` ? do you know how to access an element of a `vector`? Which part did you not find in documentation? Did you try anything? – 463035818_is_not_an_ai Dec 16 '21 at 10:04

2 Answers2

0

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
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
0

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

Ivan
  • 1,352
  • 2
  • 13
  • 31