c++ - 使用模板删除任何容器

标签 c++ visual-studio-2008 templates

我有很多代码要删除其中有指针的 vector 容器,也就是说,我必须先删除所有指针,然后再清除容器。每次我都会手动迭代并删除指针(我知道 STL::algorithms for_each)。为了规避所有这些代码,我创建了一个模板来删除所有具有指针的 vector 容器。到目前为止一切顺利。

现在我有更多的容器类型,包括映射、并发容器等。就删除而言,它们最终都具有相同的功能。 DeleteContainer(std::vector<T*>& VecIn)如上所述,我拥有的功能只能用于 vector 。有什么方法可以让它足够通用以适用于所有容器吗?

EDIT: Thanks for all the answers, I wish I could select more than one. To anybody who stumbles onto this question, read all the answers and not just the selected one as they all provide great info.

最佳答案

你已经有了一个有效的答案,但只是为了提供一个替代方案,我相信你应该考虑使用 Boost Pointer Container并让它处理内存管理:

This library therefore provides standard-like containers that are for storing heap-allocated or cloned objects (or in case of a map, the mapped object must be a heap-allocated or cloned object). For each of the standard containers there is a pointer container equivalent that takes ownership of the objects in an exception safe manner.

关于c++ - 使用模板删除任何容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479381/

相关文章:

templates - 检查类型是否是模板的实例化

c++ - 使用 boost 对多个标准容器进行基于范围的迭代的概念问题

c++ - 如何切片或访问 Tensor 的一行?

c++ - PPL:线程池的初始化

visual-studio-2008 - 在TFS下重命名VS.net中包含的项目文件夹

visual-studio - 在visual studio中显示文件夹

jquery - Visual Studio 2008 Express 和 jQuery

c++ - 初始化聚合基础(GCC 和 clang 不同意)

c++ - 在 C++ 中传递一个值以通过引用返回

javascript - 如何在 JavaScript mustache 模板上添加简单的 onclick?