Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize C++17 vector of pairs with optional element

In C++17, how do you declare and initialize a vector of pairs(or tuples) with an optional element?

    std::vector<std::pair<int, optional<bool> > > vec1 = { {1, true},                                                            {2, false},                                                             {3, nullptr}}; 

I have a pair where the second element may be null/optional.

like image 518
Eugene Avatar asked Mar 11 '20 07:03

Eugene


People also ask

How do you declare a vector vector of a pair in C++?

Here you go: #include <utility> vector<pair<int, int>> myVec (N, std::make_pair(-1, -1));

How do you declare a 2D vector of pairs in C++?

A 2D vector of pairs or vector of vectors of pairs is a vector in which each element is a vector of pairs itself. Here, dataType1 and dataType2 can be similar or dissimilar data types. Example 1: In the below C++ program, a vector of vectors of pairs of type {int, string} is used.


1 Answers

You are looking for std::nullopt instead of nullptr.

std::vector<std::pair<int, std::optional<bool> > > vec1 =   { {1, true}, {2,false}, {3,std::nullopt} }; 
like image 104
bitmask Avatar answered Oct 12 '22 01:10

bitmask