Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if pair is empty or uninitialized

Tags:

c++

std-pair

 int main() {

   pair<int, int> res;
   // check here pair is empty ?
   // res = make_pair(1 , 2);


   return 0;
}

In the above snippet what is the ideal way to check if a pair has been initilaized or not?

EDIT: As pointed out in some answers below, using the word "uninitialized" is wrong here, to be more specific how do I check if the value has been explicitly set (other than the default constructor)

like image 567
Always_Beginner Avatar asked Dec 02 '22 09:12

Always_Beginner


2 Answers

There's no such thing as unitialized std::pair.

Default constructor for std::pair will value-initialize both it's members, which for pair of ints means both int will have value 0.

like image 80
Yksisarvinen Avatar answered Dec 03 '22 23:12

Yksisarvinen


In the above snippet what is the ideal way to check if a pair has been initilaized or not?

You check your favorite language reference and realize that

  • std::pair requires default-constructible types and

  • the std::pair default constructor default-initializes its data members.

And hence,

std::pair<int, int> res;

will result in res.first and res.second both be zero.


When you need to add an additional empty state to an object, it's always an option to explicitly wrap it into a std::optional (or boost::optional if you can't use C++17). This way, you can always check whether you have a meaningful std::pair or not:

#include <optional>

std::optional<std::pair<int, int>> res;

if (res) // the pair is initialized and usable
   doStuff(*res);
else // ... it's not, hence initialize it
   res = std::make_pair(42, 43);
like image 23
lubgr Avatar answered Dec 03 '22 21:12

lubgr