简体   繁体   中英

Freeing memory for set in c++

I want to free the memory from my set. I tried how to free memory from a set post, but it didn't work for me.

This is my code:

#include <iostream>
#include <set>
using namespace std;

struct Deleter
{
    void operator () (int *ptr)
    {
        delete ptr;
    }
};

int main()
{
    set<int> myset;
    myset.insert(100);
    myset.insert(1);
    myset.insert(12);
    myset.insert(988);
    set<int>::iterator it;
    for (it = myset.begin() ; it!=myset.end() ; it++)
    {
        Deleter(it);
        cout<<"size of set: "<<myset.size()<<endl;
    }

    return 0;
}

The output is:

size of set: 4
size of set: 4
size of set: 4
size of set: 4

How does this code free the memory although the size of set is still 4? What does it delete by Deleter(it) ? If I use myset.clear() at the end, would it free all memory from set?

Thanks.

The word delete is to be used on data that has been dynamically allocated on the heap using new .

If you want to remove something from an stl set you can do so using the erase function .

If your set contained pointers to dynamically allocated objects then you could call delete on them but your set would still contain those pointers. You would still need to erase the pointers from your set.

In C++ you use delete to free up memory that was allocated when you new up an object. When you new up an object, you are saying you will manage the memory for it.

In this case, you are not newing anything up, you are simply inserting an element into the set. To remove the item from the set use the erase method.

It's overloaded a couple of different ways, so depending on if you want to remove it by iter or value you will pass different arguments. Here is a good reference for set erase.

    myset.erase(100);
    myset.erase(100);
    myset.erase(12);
    myset.erase(988);

Also, if you want to remove everything in the set, simply call the clear() method.

myset.clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM