简体   繁体   中英

How to access members inside vector of structure

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;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM