declaring an iterator inside a templated function

Hey yall, so for one of my projects I've been assigned to do some templated functions for vectors that use iterators. I can do it every other way, and maybe I'm just misunderstanding iterators, but here is what I set up for the function to print a vector. At the moment it is not working because line 4 says it needs typename before, and on line 6 it says iter is not declared in this scope. If anyone has any ideas or just some thought on iterators, I would really appreciate someone else's input!

1
2
3
4
5
6
7
8
template<typename T>
void printVector(vector <T> const &a)
{
    vector<T>::iterator iter;

    for(iter = a.begin; iter != a.end(); ++iter)
        cout << *iter << " ";
}
Last edited on
You just said how to fix it. Put 'typename' before it.
Also, you need to make it const_iterator since the vector reference is const.
Also, begin() is a function, so it needs the parens.

1
2
3
4
5
6
7
8
template<typename T>
void printVector(const vector<T> &a)
{
    typename vector<T>::const_iterator iter;

    for (iter = a.begin(); iter != a.end(); ++iter)
        cout << *iter << " ";
}

There are better ways to do it, either:

1
2
3
4
5
6
template<typename T>
void printVector(const vector<T>& v)
{
    for (auto it = v.begin(); it != v.end(); ++it)
        cout << *it << ' ';
}

Or even better:

1
2
3
4
5
6
template<typename T>
void printVector(const vector<T>& v)
{
    for (const auto& x: v)
        cout << x << ' ';
}

Last edited on
ah ok that makes a lot of sense haha, i guess i was way overthinking it since a lot of the stuff I'm doing right now is a little over my head, but now i think it makes much more sense, thank you for the help DizzyDon!
Topic archived. No new replies allowed.