There were some errors in your code. Let's look at them:
In the signature of printVector
, you take a parameter of type vector<S*>
. This means that, for a given type S
, you take a vector of pointers to S
. So, for example, if the type is int
, you should 'send' a vector<int*>
. In your example, you are attempting to 'send' a vector<int>
, so the signature of printVector
should look like this:
template <typename S>
void printVector(vector<S> c)
In your for loop, you are declaring the variable A
again, as int
. In the C++ standard library, you can access every item in a vector using iterators or just accessing them like an array. You were mixing both things.
If you want to loop using iterators, it should look like this:
typename vector<S>::const_iterator a = c.begin();
for (; a != c.end(); a++){
cout<<*a<<" ";
}
Which means, for every item in the vector, print its value (notice I used *a
because I'm using iterators).
Or using the index-based approach:
for (int i = 0; i < c.size(); i++){
cout<<c[i]<<" ";
}
Also, as a common practice in C++ community, use a const reference when receiving variables of non-primitive types. This prevents that a copy of the object is performed, so it will probably be faster when dealing with huge collections. Example:
void printVector(const vector<S>& c)
So here is a full working example:
#include <vector>
#include <iostream>
using namespace std;
template <typename S>
void printVector(const vector<S>& c){
for (int i = 0; i < c.size(); i++){
cout<<c[i]<<" ";
}
cout<<endl;
}
int main(int argc, char** args) {
vector<int> x;
int j=5;
for(int i=0;i<j;i++){
x.push_back(i);
}
printVector<int>(x); // Can be printVector(x); too
return 0;
}
` is a typo and so is `int A`. In fact I think you just wrote `int A` because you're used to seeing `int` declarations in that part of a `for` construct, but it's not correct in this case.– Lightness Races in Orbit Nov 08 '12 at 23:01