Search code examples
c++vectoroption-type

Iterate through optional vector in C++


I have an optional vector like optional<std::vector<string>> vec = {"aa", "bb"};

How can I iterate through the vector?

Doing the following:

for (string v : vec) {
    cout<<v<<endl;
}

gives the error:

error: no matching function for call to ‘begin(std::optional<std::vector<std::__cxx11::basic_string<char> > >&)’
     for (string v : vec) {
                     ^~~~~~~~~~~~~~~~~~~~~~~

How can I iterate though the optional vector?


Solution

  • Use the dereference operator on vec.

    for (string v : *vec) {
        cout<<v<<endl;
    }
    

    Note that your program will exhibit undefined behavior with this if vec.has_value() == false. So... check for that first.