My disclaimer here is that I started teaching myself C++ about a week ago and my former experience with programming has been with dynamic languages (Python, javascript).
I’m trying to iterate though the contents of a vector using a generic function to print out the items:
#include <iostream>
#include <algorithm>
#include <vector>
using std::vector;
using std::cout;
template <class T>
void p(T x){
cout << x;
}
int main () {
vector<int> myV;
for(int i = 0; i < 10; i++){
myV.push_back(i);
}
vector<int>::const_iterator iter = myV.begin();
for_each(iter, myV.end(), p);
return 0;
}
The code doesn’t compile. Would someone explain why?
Edit: The compiler error:
error: no matching function for call to 'for_each(_gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<const int, _gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >&, __gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int, __gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >, <unknown type>)'
Thanks!
Try:
There were two mistakes in your code:
There is also a nice output iterator that does this:
Also note that very few compilers can optimise code across a function pointer call.
Though most are able to optimise the call if it is an functor object. Thus the following may have been a viable alternative to a function pointer:
Another note:
When you use templated methods/functions it is usually better to pass by const reference than value. If the Type is expensive to copy then passing by value will generate a copy construction which may not be what you expected.