Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ iterator with template

Tags:

c++

iterator

I have a problem about how to use iterator under the template manner.
Here is an example I am trying to do, the problem is that, inside the for loop how can I initial the iterator pp ?

I have read a similar question, but I cannot fully understand that since I am a beginner.
What should the iterator type be in this C++ template?
Can anyone help and also provide some simple explanation?

#include <iostream>
#include <vector>

template <class T>
void my_print(std::vector<T> input){
    for(std::vector<T>::iterator pp = input.begin(); pp != input.end(); ++pp)
        std::cout << *pp << "\n";
}
int main(int argc,char* argv[]){
    std::vector<int> aa(10,9);
    my_print(aa);

    return 0;
}

error message I got:
‘std::vector::iterator’ is parsed as a non-type, but instantiation yields a type

like image 612
sflee Avatar asked Jan 01 '14 08:01

sflee


1 Answers

Add a typename before the iterator

#include <iostream>
#include <vector>

template <class T>
void my_print(std::vector<T> input)
{
    for (typename std::vector<T>::iterator pp = input.begin(); pp != input.end(); ++pp)
    {
        std::cout << *pp << "\n";
    }
}
int main(int argc, char* argv[])
{
    std::vector<int> aa(10, 9);
    my_print(aa);

    return 0;
}

source: http://www.daniweb.com/software-development/cpp/threads/187603/template-function-vector-iterator-wont-compile

like image 81
Vladp Avatar answered Oct 01 '22 13:10

Vladp