【问题标题】:template function for clearing a vector of pointers [duplicate]用于清除指针向量的模板函数
【发布时间】:2018-12-06 14:12:50
【问题描述】:

我正在尝试创建一个模板函数,它接收指向类 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

【问题讨论】:

  • ForEveR(和链接的问题)有 C++98 的正确答案。但那是二十年前的事了。今天你可以(实际上,应该)至少使用auto 来避免整个迭代器类型声明(for ( auto &amp; it = v.begin(); ...)。更好的是,使用 range-for (for ( auto &amp; it : v ))。或者最好使用smart pointers 的向量。一般来说,除非您正在处理最低级别的后端库代码(甚至可能是这样),否则您不应该再触摸newdelete。 (您仍然希望客户端记得调用您的函数...)

标签: c++ templates stl iterator


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2016-10-18
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    相关资源
    最近更新 更多