清除指针向量的模板函数

时间:2018-12-06 14:12:51

标签: c++ templates stl iterator

我正在尝试创建一个模板函数,该函数接收指向类T的某个指针的向量并清除该向量。但是,使用下面的实现,我得到编译错误。我在做什么错了?

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

1 个答案:

答案 0 :(得分:1)

您应该使用typename关键字来访问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();
}

因为您使用dependent name