iterator function arguments?

closed account (ypfz3TCk)
Suppose I have a vector<int> values. Now the pair values.begin() and
values.end() will cover the range of the vector.

I am writing a simple function that takes the pair of iterators as
arguments along with an int value. The function then returns a bool to
indicate if the int value is found in the vector.

The first problem I have is to question if it is possible to pass
iterators as distinct arguments to a function? I would have thought that
the only way to accomplish this would be to pass the vector as a
reference, from there the function can use the iterators to do it's work.

I was thinking the correct definition would be

bool find_value (vector<int>&, int);

Or is there a way to pass an iterator pair as function arguments which I
have missed? Note: without using std::find or any STL functions.
you can use templates to be able to use it for any types of iterator ( or even a plain array )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template <class RandomAccessIterator, class T>
bool find_value( RandomAccessIterator first, RandomAccessIterator last, const T& value )
{
    while( first != last ) {
        if( *first == value ) {
            return true;
        }
        ++first;
    }
    return false;
}

int main()
{
    vector<int> v = { 12, 23, 44, 102, 1 };
    bool b = find_value( v.begin(), v.end(), 44 );

    array<float, 3> a = { 23.3, 11.1, 3.14 };
    bool b2 = find_value( ... );

    char c[] = "Hello World";
    bool b3 = find_value( std::begin(c), std::end(c), ..  );
}


http://www.cplusplus.com/doc/tutorial/functions2/
Last edited on
closed account (ypfz3TCk)
I am working from C++ primer chapter 8. I don't think templates is what the authors had in mind as they have not been introduced as yet by the text. It is puzzling as there does not seem to be any obvious way to use iterators as function arguments.
Here's a version of nvrmnd's answer that doesn't use templates (note: this one only works for std::vector<int>):
1
2
3
4
5
6
7
8
9
10
bool find_value(std::vector<int>::const_iterator start, std::vector<int>::const_iterator end, int value)
{
    while (start != end)
    {
        if (*start == value)
            return true;
        ++start;
    }
    return false;
}
Last edited on
Topic archived. No new replies allowed.