How to check if **any** element exists in an `std::vector` at a given index

Morpheus :

I have an std::vector like this

std::vector<std::pair<T,T>> xyz. xyz has a length of 10 and another function fills exactly 3 spots, say 4, 6, and 8 with std::pair<T,T>. While iterating through the vector, I want to know where the non-empty spots are there so that I can further work with the std::pair<T,T>s.

I think I can use c++17's std::optional<> but I am using c++14. Is there any way to find out the spots in an std::vector which are not empty in c++14.

the vector will look something like this after assignment from the function

index  value
 0:
 1:
 2:
 3:
 4:    <7,8>
 5:
 6:    <9,2>
 7:
 8:    <8,6>
 9:

I want to iterate over the above vector and only say print the std::pairs

John Ding :

You cannot do it if you don't do some work on your data-structure, for every element in vector is initialized.

The simplist and quickest way I think, is to store a std::vector<bool> of the same size to store whether a element is not only initialized, but "modified" later as well.

If you worry that you may forget to set the other vector, bind them together:

std::vector<std::pair<std::pair<int, int>, bool>> a;

If you still think this is too ugly, you may have to implement your own simple optional

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=404600&siteId=1