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!
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()) { .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With