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)
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With