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

user1634426 picture user1634426 · Sep 24, 2015 · Viewed 8.7k times · Source

What would I want to use instead of NULL if I have an unassigned pair in C++?

As an example, suppose I have (pseudo)code like the following:

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

Answer

utnapistim picture utnapistim · Sep 24, 2015

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

No.

What would I want to use instead of NULL if I have an unassigned pair in C++?

Here are a few options:

  • you can use a pointer to a pair, which can be set to NULL; This is probably not the best solution (since you are clearly not requiring a pointer)

  • you can use a boost::optional<std::pair<int,int>>;

  • you can (and probably should) rewrite your code not to use a global variable.

  • you can restructure your control flow to avoid checking for a valid pair as a separate step:

    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;
    }
    
  • you can choose an artificial value to represent "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());
    
  • you can use a boolean flag:

    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;
    }
    
  • you can use a custom solution (similar to boost::optional wrapper or not)