微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c – 使用模板删除任何容器

我有很多代码,我在删除在其中有指针的向量容器,也就是说,我必须首先删除所有的指针,然后清除容器.每次我会遍历并手动删除指针(我知道stl :: algorithms for_each).为了规避所有的代码,我创建了一个模板,用于删除所有具有指针的向量容器.到现在为止还挺好.

现在我有几个容器类型,包括地图,并发容器等,到目前为止,所有功能都有相同的功能,只要删除.我拥有的DeleteContainer(std :: vector< T *& VecIn)函数只能在上面提到的向量上工作.有没有什么办法使其通用到足以在所有容器上工作?

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.

原文地址:https://www.jb51.cc/c/114787.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐