0

I want to traverse a vector but I don't know it's type before hand.So,I do the following : -

template<typename T>
vector<int> sas_v(vector<T>vT,T val)
    {
      vector<int>il; //index_list
      vector<T>::iterator it;
      for(it = vT.begin();it!=vT.end();it++)

          {
             if(*it==val)
             il.push_back(it-vT.begin()); //0 based indexing
          }

      return il;
   }

But I get bunch of errors.Though if I do this following way it works,Why?

template<typename T>
vector<int> sas_v(vector<T>vT,T val)
{
    vector<int>il; //index_list
//    vector<T>::iterator it;
   // for(it = vT.begin();it!=vT.end();it++)
    for(int a=0;a<vT.size();a++)
    {
        if(vT[a]==val)
            il.push_back(a); //0 based indexing
    }

    return il;
}
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
  • use `typename vector::iterator it;` – Piotr Skotnicki Sep 25 '15 at 10:39
  • 2
    If you say "I get bunch of errors", what errors do you mean? In the future, please also post the error messages! – anderas Sep 25 '15 at 10:44
  • 1
    If you have a new enough compiler, just use `auto`. The pain of getting iterator types properly declared inside template functions was one of the flaws in C++ as a language. It is a flaw that has been fixed. If stuck with an older compiler, others already told you about the use of `typename` – JSF Sep 25 '15 at 10:52

0 Answers0