1

我有以下功能,以前可以正常工作,但是,我不知道我做了什么,我开始得到一些奇怪的错误

容器是一个指针向量

template<typename Container>
void delete_collections(Container& c) 
{ 
    while(!c.empty()) 
    {
        delete c.back(); //<=== here
        c.back() = NULL;
        c.pop_back();    //<=== & here
    }
}

第一个错误

* *此行有多个标记

  • (每个未声明的标识符都是
  • `back' 未声明(首先使用这个

第二个错误

  • `pop_back' 未声明(第一次使用

解决方案 我曾经错误地将映射传递给函数,但我希望编译器给出任何警告。

4

1 回答 1

2

Just for the record, I would use a specialized container instead, take a look at e.g. Boost. Alternatively, store smart pointers where you don't have to call delete manually. Still, here's how to do it in a way that works with every container except maps:

template<typename container>
void delete_all(container& c) {
    for(typename container::const_iterator it=c.begin(), end=c.end(); it!=end; ++it)
        delete *it;
    c.clear();
}

With C++11, you could use auto, too, instead of typename container::const_iterator.

于 2013-07-19T19:30:58.710 回答