Template find()

Is there another way to increment the iterator while still keeping the const of beg? This works fine for vectors but I guess the compiler is freaking out when it comes to list iterators.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<iostream>
using std::cout;

#include<list>
using std::list;

#include<vector>
using std::vector;

#include<string>
using std::string;

template <typename ITER, typename V>
ITER find(const ITER &beg, const ITER &end, const V &sought)
{
    while (beg != end)
    {
        if (*beg == sought)
            return beg;

        return (beg + 1, end, sought);
    }
    return end;
}

int main()
{
    list<string> li { "Hello", "World"};

    auto res = find(li.begin(), li.end(), "World");

    cout << *res;
}
Prefer passing iterators by value.
1
2
3
4
5
6
template< typename ITER, typename V >
ITER find( ITER beg, const ITER& end, const V& sought )
{
    if( beg == end || *beg == sought ) return beg ;
    return find( ++beg, end, sought ) ;
}


If you are experimenting with pass by reference, make a copy and modify the copy.
1
2
3
4
5
6
7
template< typename ITER, typename V >
ITER find2( const ITER& beg, const ITER& end, const V& sought )
{
    if( beg == end || *beg == sought ) return beg ;
    ITER cpy = beg ;
    return find( ++cpy, end, sought ) ;
}


If you want to get cute, tag-dispatch:
1
2
3
4
5
6
7
8
9
10
11
12
template< typename ITER >
ITER next( const ITER& iter, std::random_access_iterator_tag ) { return iter+1 ; }

template< typename ITER >
ITER next( ITER iter, std::input_iterator_tag ) { return ++iter ; }

template< typename ITER, typename V >
ITER find3( const ITER& beg, const ITER& end, const V& sought )
{
    if( beg == end || *beg == sought ) return beg ;
    return find( next( beg, typename std::iterator_traits<ITER>::iterator_category() ), end, sought ) ;
}
Thanks for the examples. The 2nd one doesn't seem to work though but I get the idea, and the 3rd just flies over my head, gonna have to take a look at that closely, thanks again.
> the 3rd just flies over my head, gonna have to take a look at that closely

This might help.
http://www.boost.org/community/generic_programming.html#tag_dispatching
Topic archived. No new replies allowed.