在c++中是否有NULL等价的pair ?

Is there a NULL equivalent for pairs in C++?

本文关键字:pair NULL c++ 是否      更新时间:2023-10-16

如果我在c++中有一个未分配的对,我想使用什么而不是NULL ?

例如,假设我有如下的(伪)代码:
pair<int,int> bestPair; //Global variable
updateBestPair(vector<int> a, vector<int> b) {
    bestPair = NULL;
    for (/* loop through a and b */) {
        if (/* pair(a,b) is better than bestPair and better than some baseline */)
            bestPair = make_pair(a,b);
    }
    if (bestPair != NULL) //Found an acceptable best pair
        function(bestPair);
    else
        cout<<"No acceptable pairs found"<<endl;
}

在c++中对是否有NULL等价?

如果我在c++中有一个未分配的对,我想用什么代替NULL ?

这里有几个选项:

  • 可以使用指向pair的指针,可以设置为NULL;这可能不是最好的解决方案(因为您显然不需要指针)

  • 你可以使用boost::optional<std::pair<int,int>>;

  • 你可以(也许应该)重写你的代码,不使用全局变量

  • 你可以重组你的控制流,以避免检查一个有效的对作为一个单独的步骤:

    pair<int,int> bestPair; //Global variable
    updateBestPair(vector<int> a, vector<int> b) {
        // not needed
        // bestPair = NULL;
        //loop through a and b
        if (/* pair(a,b) is better than bestPair and ... */)
        {
            bestPair = make_pair(a,b);
            function(bestPair);
        }
        else
            cout<<"No acceptable pairs found"<<endl;
    }
    
  • 你可以选择一个人工值来表示"invalid pair value":

    // use as constant, wherever you used NULL before
    const auto invalid_pair = std::make_pair(
        std::numeric_limits<int>::max(),
        std::numeric_limits<int>::max());
    
  • 你可以使用布尔标志:

    pair<int,int> bestPair; //Global variable
    updateBestPair(vector<int> a, vector<int> b) {
        bool initialized = false;
        //loop through a and b
        if (/* pair(a,b) is better than bestPair and ... */)
        {
            bestPair = make_pair(a,b);
            initialized = true;
        }
        if(initialized)
            function(bestPair);
        else
            cout<<"No acceptable pairs found"<<endl;
    }
    
  • 您可以使用自定义解决方案(类似于boost::可选包装或不)

No。c++对象不能为" null "

(即使指针是对象,也不能被" null "!)这是令人困惑的,因为它们的值可能被设置为空指针值,我们过去有时通过名为NULL的宏获得;然而,这与指针本身的"空"是不一样的。呃,anyway…)

我推荐boost::optional,或者重新考虑拥有一个全局变量的想法,可以是"有一个有用的值"或"没有一个有用的值"。如果它没有有用的价值,存在的意义是什么?

不,那不可能。您可以使用一个额外的变量来指示对的有效性(您有一个对)。