deleting a vector of points

Hi all, following is the code I think will delete all the objects that the elements(pointers) in my vector point to and also the elements(pointers) in my vector. In short deleting a vector of pointers without creating any memory leaks.

vector<Tickets *> tckts;
int i;
i=tckts.size();
vector<Ticket *>::iterator it;
for(it=tckts.begin();it!=tckts.end();it++)
delete *it;
tckts.erase(tckts.begin(),tckts.end());

Am I doing it correctly? Thanks in advance.
That .erase is useless. It will be don by vector's destructor. Otherwise it looks fine.
Hi , I have a quick question
can we delete like this .

1
2
3
4
5
6
7
8
vector<Tickets *> tckts;
Tickets* ptickets;
int i;
i=tckts.size();
for( int j = 0 ; j < i ; j++) 
ptickets = it.at(j);
delete ptickets; 
tckts.erase(tckts.begin(),tckts.end());


Thanks in advance ;


You forgot to wrap your loop in {}s. And .erase is still useless. Otherwise it's fine.
If you are reusing a vector, and want to clear all its contents, then

tckts.clear();

does the same as you erase statement.

Incidentally, you can tighten up the scope of your variables (inc the {}s hamsterman mentioned, etc)

1
2
3
4
5
6
7
vector<Tickets *> tckts;
for( int j = 0, i = tckts.size(); j < i ; j++)
{
    Tickets* ptickets = tckts.at(j); // not it
    delete ptickets; 
}
tckts.clear();
If I dont want to reuse my vector and just want to delete it completely then is my code ok? I din't get you @hamsterman, do you mean .erase won't completely delete the vector?
erase will delete the vector, but the vector was going to delete itself anyway.
thanks hamsterman . ..
As hamsterman said, a vector will delete itself (plus the storage it allocated) when it goes out of scope. You only need to clear vectors if you are reusing them, or - for example - if they're a member variable of some other class which won't go out of scope immediately.

When erasing all elements is an array, v.clear() is preferred to v.erase(v.begin(),v()) as the clear() algorithm is optimized for this special case.

But note that clear() does call the destructor for all the elements, it does not free all the memory the vector holds (has reserved). If you call v.size(), after v.clear(), you will get 0; but v.capacity() will return at least the number of elements you had added to the vector (implementations are allowed to reserve more space than immediately required).

To really free all the memory, you need to use swap().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
using namespace std;

class Tickets
{
    // dummy class
};

void test()
{
    const int count = 4;

    vector<Tickets *> tckts;

    cout << "add tickets" << endl;

    for( int j = 0; j < count; j++)
    {
        tckts.push_back(new Tickets());
    }

    cout << "delete all tickets and clear" << endl;

    for( int j = 0, i = tckts.size(); j < i ; j++)
    {
        Tickets* ptickets = tckts.at(j);
        delete ptickets; 
    }

    tckts.clear();
    // or tckts.erase(tckts.begin(), tckts.end());

    cout << "- size     = " << tckts.size()     << endl;
    cout << "- capacity = " << tckts.capacity() << endl;

    cout << "and swap!" << endl;

    vector<Tickets *>( tckts ).swap( tckts );

    cout << "- size     = " << tckts.size()     << endl;
    cout << "- capacity = " << tckts.capacity() << endl;
}

int main(){

    test();

    return 0;
}


add tickets
delete all tickets and clear
- size     = 0
- capacity = 4
and swap!
- size     = 0
- capacity = 0
Last edited on
oh really, @hamsterman you mean once it goes out of scope?
I'm having trouble with deleting a single vector element(pointer) after assigning it to a pointer. Here is my code:

void deleteEmp()
{
Employee temp;
long i;
bool found=false;
cout<<"Enter the employee's ID to be deleted:\t";
cin>>i;
cin.ignore();
temp.setEmpId(i);
vector<Employee *>::iterator iter=emps.begin();
while(iter!=emps.end())
{
if(temp==*(*iter))
{
found=true;
cout<<"Employee record with Emp ID "<<(*iter)->getEmpId()<<" is deleted.\n";
break;
}
iter++;
}
if(found==true)
{
/////////copying everything from the fired employee to the new employee
Employee *e;
e=new Employee;
e=(*iter);
e->populate();
emps.push_back(e);

//////////actual deletion of the fired employee
(*iter)->deleteEmpTckts();////I'm getting the assertion error at this line
delete *iter;
emps.erase(iter);
}
else
cout<<"The employee record with the requested ID does not exist!"<<endl;
}

The error is: 'Debug Assertion failed', Program:.......include\vector Line: 70,
Expression:vector iterator not dereferencable.

Thank you.
Wow @andywestken, you explain very well. Thank you for taking your time to do the explaining and coding. i know how to delete a vector now.
One last clarification: What exactly happens here ---Tickets* ptickets = tckts.at(j);---
my understanding:
The Tickets ptr 'ptickets' will be assigned to Tickets ptr at the position 'j' of the vector 'tckts'.

Did I get it right?
1
2
3
4
5
6
7
8
9
10
if(found==true)
{
/////////copying everything from the fired employee to the new employee
Employee *e;
e=new Employee;
e=(*iter);
delete e;


}


Is this right
Last edited on
@andywestken

What exactly happens at ????? vector<Tickets *>( tckts ).swap( tckts );

When I googled the swap vector operation I dint see any examples that used swap like u did. All the examples were about swapping elements between two vectors like in the line below.
swap(vector& v2) --- Swaps contents of two vectors. Declaration: void swap(vector&)

Thank you for your time.
@bluecoder, I don't think that will delete the element in the vector. Right?
You better use a smart pointer (please tell me that you are using polymorphism)

1
2
3
4
5
6
7
8
9
10
11
12
13
//copying everything from the fired employee to the new employee
//¿eh? ¿why is there a new employee?
Employee *e;
e=new Employee;
e=(*iter); //memory leak

e->populate();
emps.push_back(e); //this could invalide the iterators (reallocation)

//this is no longer safe
(*iter)->deleteEmpTckts();
delete *iter;
emps.erase(iter);
@ne555 oh my God yes, my code is so flawed. Thank you for pointing it out.
I think I should write an operator overloading function for an assignment operator '=' , if e=(*iter) has to work without any memory leaks. I guess it should actually be *e=**iter.
Topic archived. No new replies allowed.