1

I want to define a helper function that takes a template parameter. I have tried making a templated function for this, but it does not compile. Any idea what I'm doing wrong? Here's the code I tried.

// vectors are great, but lack a find method. Implement one as a helper.
template<class T> bool vec_find(vector<T> &v, T obj)
{
    vector<T>::iterator s;
    for (s = v.begin(); s < v.end(); s++)
    {
        if (*s == obj)
        {
            return true;
        }
    }
    return false;
}
GregC
  • 7,737
  • 2
  • 53
  • 67
  • Did you place this in a header file? What's the compiler error? – GregC Jun 15 '12 at 17:19
  • 7
    Use `std::find`. – Cat Plus Plus Jun 15 '12 at 17:22
  • 3
    I think you'll need a `typename` before `vector::iterator`. Also, you should never use `s < v.end()` with iterators. For vectors, where storage is contiguous, it might work fine, but then when you move to something like `std::list`, you'll get unexpected results. Better yet, you can used ranged-for or `std::for_each`. – chris Jun 15 '12 at 17:23
  • Or you could use `std::binary_search` when your vectors are sorted. – bbtrb Jun 15 '12 at 17:24
  • possible duplicate of [Where and why do I have to put the "template" and "typename" keywords?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – Mike Seymour Jun 15 '12 at 17:42

1 Answers1

1

Presumably, your compiler told you what the problem was. Mine said:

test.cpp:7:5: error: need ‘typename’ before ‘std::vector<T>::iterator’ because ‘std::vector<T>’ is a dependent scope

So to fix it, add typename before vector<T>::iterator:

typename vector<T>::iterator s;
^^^^^^^^

In general, you need that whenever the scope of a type name depends on a template parameter; until the template is instantiated, the compiler doesn't know how vector<T> will be defined, and so needs to be told that a name scoped inside it refers to a type rather than something else.

However, there is a good reason why vector doesn't have a find method: the C++ library separates containers from the algorithms that act on them, so that any algorithm can act on any suitable sequence. You want to use std::find for this:

return std::find(v.begin(), v.end(), obj) != v.end();
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644