C++ pairs and pointers

c++, pointers, std-pair

Solution

Try passing in a pair to foo() by reference, then returning a bool from that function indicating success or failure. Like so:

bool foo(pair<int, int>& myPair) {
  if(cond) {
    myPair = std::make_pair(1,2);
    return true;
  }
  return false;
}
void boo() {
  pair<int, int> myPair;
  if (!foo(myPair)) {
    // doA
  } else {
    int a = myPair.first;
    int b = myPair.second;
    // doB
  }
}

Edit: Depending on what you're doing, you should just kill `foo()` if possible and evaluate `cond` within `boo()`

void boo() {
  pair<int, int> myPair;
  if (!cond) {
    // doA
  } else {
    myPair = std::make_pair(1,2);
    int a = myPair.first;
    int b = myPair.second;
    // doB
  }
}

Problem

I don't know what can I do to make this work in C++. The intend is: ``` pair<int, int> foo() { if(cond) { return std::make_pair(1,2); } return NULL; //error: no viable conversion from 'long' to 'pair<int, int> } void boo() { pair<int, int> p = foo(); if (p == NULL) { //error: comparison between NULL and non-pointer ('int, int' and NULL) // doA } else { int a = p.first; int b = p.second; // doB } } ``` Since I cannot use return NULL in C++, here is my 2nd try: ``` pair<int, int>* foo() { if(cond) { return &std::make_pair(1,2); //error: returning address of local temporary object) } return nullptr; } void boo() { pair<int, int>* p = foo(); if (p == nullptr) { // doA } else { int a = p->first; int b = p->second; // doB } } ``` What is the correct way to be able to return a pair and a null value.

Original source