0

I want to print the elements of the vector. The following is my code.

This is my code

After searching I found the following code and its working:

for(int i=0;i<vec.size();i++)
    cout<<vec[i]<<" ";

But can't we use iterators to access the elements? if possible, how?

ForceBru
  • 36,993
  • 10
  • 54
  • 78
Ananthi
  • 1
  • 1

2 Answers2

3

typename is missing:

template <typename T>
void printArray(const std::vector<T>& a)
{
    for (typename std::vector<T>::const_iterator it = a.begin(); it != a.end(); ++it) {
        // ...
    }
}

In c++11, you may simply wrote:

template <typename T>
void printArray(const std::vector<T>& a)
{
    for (const auto& e : a) {
        std::cout << e << std::endl;;
    }
}
Jarod42
  • 173,454
  • 13
  • 146
  • 250
0

You can just do auto it = vec.begin() in case you're using C++11 so you don't really need to worry about the type of it.

ForceBru
  • 36,993
  • 10
  • 54
  • 78