0

I'm trying to create a template function which receives a vector of some pointer to class T and clears the vector. However, with the below implementation I get compilcation errors. What am I doing wrong?

template <class T>
void clearVectorOfPointers(vector<T>& v){
for (vector<T>::iterator it = v.begin(); it != v.end(); ++it){
    delete (*it);
}

v.clear();
}

symbolTable.cpp: In function ‘void clearVectorOfPointers(std::vector<T, std::allocator<_CharT> >&)’:
symbolTable.cpp:8: error: expected ‘;’ before ‘it’
symbolTable.cpp:8: error: ‘it’ was not declared in this scope
max66
  • 65,235
  • 10
  • 71
  • 111
ekosman
  • 300
  • 2
  • 13
  • ForEveR (and the linked question) have the correct answer for C++98. But that was two decades ago. Today you could (indeed, *should*) at least use `auto` to avoid the whole iterator type declaration (`for ( auto & it = v.begin(); ...`). Better, use a range-for (`for ( auto & it : v )`). Or best, use a vector of [smart pointers](https://en.cppreference.com/w/cpp/memory). Generally speaking, unless you're working the lowest levels of back-end library code (and probably even then), you shouldn't touch `new` or `delete` anymore. (You still expect the client to remember calling your function...) – DevSolar Dec 06 '18 at 14:28

1 Answers1

1

You should use typename keyword to access typedef iterator

template <class T>
void clearVectorOfPointers(vector<T>& v){
for (typename vector<T>::iterator it = v.begin(); it != v.end(); ++it) 
{
    delete (*it);
}

v.clear();
}

cause you use dependent name.

ForEveR
  • 55,233
  • 2
  • 119
  • 133