Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify if vector iterator has reached end of vector?

I have a vector of integers and I want my iterator to point to my desired number (call it 'test').

vector<int> vec;
void find(std::vector<int>::iterator iter, int test)
{
    if((*iter)!=test){ ++iter;}
}

That is sometimes problematic because iter might hit the end of the vector (if 'test' is not in the vector) and I'll run into an error.

Is there anyway I can perform something like

if(iter!=vec.end())

and stop the iteration without specifying my vector in the function? Thank you!

like image 912
Dinosaur Avatar asked Jan 08 '23 05:01

Dinosaur


1 Answers

You can take the standard library approach and pass a pair of iterators to the function:

template <typename Iterator>
void foo(Iterator begin, Iterator end,
         typename std::iterator_traits<Iterator>::value_type test)
{
  Iterator it = begin;
  ....
  if (iterator != end) { ... }
}

Then you have to figure out an algorithm to find the iterator pointing to an element with value equal to test. Or just call std::find and drop your function.

auto it = std::find(vec.begin(), vec.end(), test);
if (it != vec.end()) { .... }
like image 84
juanchopanza Avatar answered Jan 14 '23 03:01

juanchopanza