容器中有些指针自己不会自动清除
能够清除任何序列容器中的指针的函数模板
//: :purge.h
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Delete pointers in an STL sequence container.
#ifndef PURGE_H
#define PURGE_H
#include <algorithm>
template<class Seq> void purge(Seq& c) {
typename Seq::iterator i;
for(i = c.begin(); i != c.end(); ++i) {
delete *i;
*i = 0;
}
}
// Iterator version:
template<class InpIt> void purge(InpIt begin, InpIt end) {
while(begin != end) {
delete *begin;
*begin = 0;
++begin;
}
}
#endif // PURGE_H ///:~
注意关键字typename是绝对必须的
关键字是设计用来解决问题的
purge()容器版本必须与一个STL风格的容器一起工作
purge()的迭代器版本的工作区域