2

I'm trying to create a template function that takes a vector argument of any type T (primitive for now) and prints out its contents:

template<class T>
void displayContents(const vector<T>& data)
{
    vector<T>::const_iterator i;
    i=data.begin();

    for( ; i!=data.end(); i++){
        cout<<*i<endl;
    }
}

The error message is:

In function 'void displayContents(const std::vector >&)': error: expected ';' before 'i' | error:'i' was not declared in this scope === Build finished: 2 errors, 0 warnings ===

Am I overlooking a syntax error?

Zubizaretta
  • 157
  • 1
  • 9

2 Answers2

5

Try the following:

  typename vector<T>::const_iterator i;

As pointed out by Björn in the comment already, it is needed because is a dependent name of the template.

Krizz
  • 11,362
  • 1
  • 30
  • 43
3

If your goal is to output every element, you shouldn't constrain yourself to vectors. The idiomatic, generic solution is to pass two iterators instead:

template<typename ForwardIterator>
void display_contents(ForwardIterator begin, ForwardIterator end)
{
    for (ForwardIterator it = begin; it != end; ++it)
    {
        std::cout << *it << '\n';
    }
}

Then you can use the template with vectors, sets and practically all other containers:

int main()
{
    std::vector<int> a {2, 3, 5, 7};
    display_contents(a.begin(), a.end());

    std::set<int> b {11, 13, 17, 19};
    display_contents(b.begin(), b.end());
}
fredoverflow
  • 256,549
  • 94
  • 388
  • 662