返回顶部

收藏

C++ 如何删除动态分配的SLT容器

更多
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// These can be used to delete container elements
// that have been dynamically allocated.

// Use with transform
template<typename T>
class DeletePtrTr
{
public:
    T* operator()(const T* p) { delete p; return 0; }
};

// Use with for_each
template<typename T>
class DeletePtrFe
{
public:
    void operator()(T*& p) { delete p; p = 0; }
};

/* 用法 */
int _tmain(int argc, _TCHAR* argv[])
{
    vector coll;
    vector::const_iterator it;

    // Add ten integer pointers (values 1 to 10)
    for (int i = 1; i <= 10; i++)
    {
        coll.push_back(new int(i));
    }

    // Print contents (values)
    cout << "Values" << endl << endl;
    for (it = coll.begin(); it != coll.end(); ++it)
    {
        int value = **it;
        cout << value << endl;
    }
    cout << endl;

    // Deallocate memory using for_each or transform
    for_each(coll.begin(), coll.end(), DeletePtrFe());
    //transform(coll.begin(), coll.end(), coll.begin(), DeletePtrTr());

    // Print contents (null pointers)
    cout << "Deleted pointers" << endl << endl;
    for (it = coll.begin(); it != coll.end(); ++it)
    {
        int* ptr = *it;
        cout << ptr << endl;
    }

    return 0;
}

标签:C++,删除SLT容器,动态分配

收藏

1人收藏

支持

1

反对

0

相关聚客文章
  1. Qiang 发表 2011-09-08 14:06:35 Lexing Python Indentation using Spirit.Lex
  2. 霜天 发表 2013-03-22 03:58:33 分享两个强符号,弱符号引起的编译问题
  3. Herb Sutter 发表 2012-04-30 21:36:26 C++ and Beyond Panel: Modern C++ = Clean, Safe, an
  4. Herb Sutter 发表 2012-09-01 00:43:58 Reader Q&A: How to write a CAS loop using std::ato
  5. Herb Sutter 发表 2013-01-01 17:34:09 Video: You Don’t Know const and mutable
  6. Sana Mithani 发表 2013-02-26 20:32:00 The C++ REST SDK ("Casablanca")
  7. bystander 发表 2013-04-11 00:45:38 并查集(C++实现)
  8. bystander 发表 2013-05-22 08:16:24 引用和指针(C++)
  9. mortoray 发表 2013-06-03 04:25:59 Overloading the broken universal reference ‘T&&’
  10. Jim Hogg 发表 2013-07-04 20:00:00 Optimizing C++ Code : Constant-Folding
  11. Todd 发表 2013-08-09 02:18:31 数据即代码:元驱动编程
  12. wuyuan 发表 2013-09-21 10:47:46 函数指针总结