Dinosaur
Dinosaur

Reputation: 675

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!

Upvotes: 4

Views: 5021

Answers (4)

juanchopanza
juanchopanza

Reputation: 227468

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()) { .... }

Upvotes: 8

Marco A.
Marco A.

Reputation: 43662

A pair of thoughts:

  1. You're passing the iterator by value
  2. Standard Library usually works by passing a begin-end couple so you can adjust your range as you wish

I'd go for something like

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

int main()
{
    vector<int> a = { 2,3,4 };
    std::vector<int>::iterator it = a.begin();
    find(it, a.end(), 5);
}

Example

Anyway you could just use std::find (http://en.cppreference.com/w/cpp/algorithm/find)

Upvotes: 2

user1641854
user1641854

Reputation:

Use standard algo std::find, from <algorithm>

auto it = std::find(vector.begin(), vector.end(), value);

Upvotes: 1

Technoid
Technoid

Reputation: 435

Yes, vec.end() is present. You can check this reference http://www.cplusplus.com/reference/vector/vector/end/

Upvotes: -2

Related Questions