lundi 6 mai 2019

How to handle std::find_if() returning false?

Take the following example taken from the cplusplus.com reference page and altered to return false:

// find_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::find_if
#include <vector>       // std::vector

bool IsOdd (int i) {
  return ((i%2)==1);
}

int main ()
{
  std::vector<int> myvector;    
  myvector.push_back(10);
  myvector.push_back(20);
  myvector.push_back(40);
  myvector.push_back(50);

  std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
  std::cout << "The first odd value is " << *it << '\n';

  return 0;
} 

Since no value in myvector is odd it will return InputIterator last, which is undefined.

The first odd value is -1727673935

What is the proper way to handle this output?

How can I know std::find_if() returned false if the output is unpredictable and comparing to the entire vector to confirm the resulting value doesn't exist defeats the purpose of using std::find_if() to begin with?

Aucun commentaire:

Enregistrer un commentaire