Check if pair is empty or uninitialized

会有一股神秘感。 提交于 2020-12-12 05:28:35

问题


 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)


回答1:


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.




回答2:


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);



回答3:


This depends on how you define the std::pair is empty. The default constructor of std::pair would value-initialize both elements of the pair, that means for pair<int, int> res;, its first and second would be initialized to 0. That's the only way you can check for a default-constructed std::pair, if they're guaranteed to be non-zero after the assignment.




回答4:


You can write a function similar to the following

namespace usr
{
    template <class T1, class T2>
    bool empty( const std::pair<T1, T2> &p )
    {
        return p == std::pair<T1, T2>();
    }
}

That is a default initialized pair will be considered as ampty.

Here is a demonstrative program

#include <iostream>
#include <utility>

namespace usr
{
    template <class T1, class T2>
    bool empty( const std::pair<T1, T2> &p )
    {
        return p == std::pair<T1, T2>();
    }
}

int main()
{
    std::pair<int, int> p1( 1, 2 );

    std::cout << usr::empty( p1 ) << '\n';

    std::pair<int, int> p2;

    std::cout << usr::empty( p2 ) << '\n';
}

Its output is

0
1


来源:https://stackoverflow.com/questions/57109084/check-if-pair-is-empty-or-uninitialized

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!