tags:

views:

43

answers:

2

I tried with this piece of code but it didn't work

template <class T>
void display(vector<T> vec)
{
  vector<T>::iterator MyIter;
  for(MyIter=vec.begin();MyIter!=vec.end();MyIter++)
    cout<<*MyIter<<" ";
  cout<<endl;
}

I mean if there's a way of avoid making a function for each type T (int, char, string). I'm using only builtin types for T.

This is the error message when I compile the program

10 C:\Documents and Settings\ASPIRE\Desktop\perms.cpp expected `;' before "MyIter" 
A: 

Can you be more clear on how this code did not work?

It relies on the existence of T::operator<< - if that is not present for any instantiating type/class T that you use in your code, the code will not compile. For builtin types this code would work OK. If you are using this for vector of your own types then you would have to implement operator<< for each for this to work.

btw use ++MyIter, it's more efficient.

Steve Townsend
why is ++Myiter more efficient?
rfrm
Because the other form has to do an extra copy constructor call in order to return the correct value. Check the prefix and postfix increment declarations in your <vector> header file. See also duffymo's response here : http://stackoverflow.com/questions/1812990/incrementing-in-c-when-to-use-x-or-x
Steve Townsend
+2  A: 

You are missing the typename infront of the variable definition MyIter i.e. it should be typename vector<T>::iterator MyIter;

Naveen