Write a function that takes a pair of iterators to a
vector<int> and an int value. Look for that value in the range and return
a bool indicating whether it was found.
Exercise 9.5: Rewrite the previous program to return an iterator to the
requested element. Note that the program must handle the case where the
element is not found.
For the first one I returned true for a match, false otherwise. Now for the second part I return the iterator (in place of true):
using vectInt_ConstIter = std::vector<int>::const_iterator;
inline vectInt_ConstIter checkVectorForVal( vectInt_ConstIter cbeg, vectInt_ConstIter cend, int nCheckValue )
{
while ( cbeg != cend )
{
if ( *cbeg == nCheckValue )
{
return cbeg; // match! Return iterator to that element
}
++cbeg;
}
return ???; // value did not match an element
}
// in main():
int main()
{
std::vector<int> vect{ 10, 20, 30, 40, 50 };
vectInt_ConstIter it = checkVectorForVal( vect.cbegin(), vect.cend(), 30 );
// ...
return 0;
}
But I'm not exactly sure of what to return if no match is found??? I thought of nullptr, but that gives an error.
using vectInt_ConstIter = std::vector<int>::const_iterator;
// RETURN BOOL IF VALUE IS IN AN ELEMENT OR NOT
inlinebool isInVector( vectInt_ConstIter cbeg, vectInt_ConstIter cend, int nCheckValue)
{
while ( cbeg != cend )
{
if ( *cbeg == nCheckValue )
{
returntrue; // match
}
++cbeg;
}
returnfalse; // no match
}
// RETURN ITERATOR TO ELEMENT THAT MATCHES VALUE, ELSE RETURN OFF-THE-END ITERATOR
inline vectInt_ConstIter isInVector( vectInt_ConstIter cbeg, vectInt_ConstIter cend, int nCheckValue )
{
while ( cbeg != cend )
{
if ( *cbeg == nCheckValue )
{
return cbeg; // match
}
++cbeg;
}
return cend; // no match
}
I thought of doing it with an un-named parameter, i.e.:
inlinebool isInVector( vectInt_ConstIter cbeg, vectInt_ConstIter cend, int nCheckValue, int)
I could use a type alias called DUD, and pass a macro with a similar name or something, but I figured this might be sloppy? Is this good or bad, or is there another better practice?
it doesn't really save typing as you still have to implement two functions (which kind of defeats the purpose of templates) and you have to explicitly state the return type when you call the function.