Home > Back-end >  Iterate through optional vector in C
Iterate through optional vector in C

Time:03-01

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?

CodePudding user response:

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.

CodePudding user response:

The below code works:

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

int main()
{
    std::optional<std::vector<std::string>> vec({ "aa", "bb" });

    if (vec.has_value()) // If vec has a value
    {
        for (auto& v : vec.value()) 
        {
            std::cout << v << std::endl;
        }
    }
}

Here in the above code, I am iterating through the elements of the vector by using vec.value().

  • Related