Is there any thing wrong in this vector code ?

I am tying to delete those customer whose age is 15
So entered the data as 12,13,14,15,16,15,17,15,18,15.
Size is 10 and capacity is 10.
After deleting the customer whose age is 15, still the size is 10 and capacity is 10.
The size should be 6.

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
51
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class customer {
    int Age;
    public:
    customer(int a) : Age(a){
        cout << "Customer created for Age:" << a << endl;
    }
    ~customer() {
        cout << "Destroyed for age " << Age << endl;
    }
    int getAge() const {
        return Age;
    }
};
template<typename T>
struct DeleteCust {
    private:
        T value;
    public:
        DeleteCust(T a) : value(a) {}
        void operator()(const customer* obj) const {
            if(value == obj->getAge())
                delete obj;
    }
};
int main() {
    std::vector<customer*> vect;
    vect.reserve(10);
    for( int i=0; i<10; i++) {
       int Age;
       cout << "Enter Age:" ;
       cin >> Age;
       vect.push_back(new customer(Age));
    }
    cout << "size is" << vect.size() << endl;
    cout << "Capacity is" << vect.capacity() << endl;
    int Age;
    cout << "Enter the age to delete:";
    cin >> Age;
    for_each(vect.begin(),vect.end(),DeleteCust<int>(Age));
    vect.erase(remove(vect.begin(),vect.end(),static_cast<customer*>(NULL)),vect.end());
    cout << "size is" << vect.size() << endl;
    cout << "Capacity is" << vect.capacity() << endl;
    //vect.push_back(new customer(Age));
    //cout << "size is" << vect.size() << endl;
    //cout << "Capacity is" << vect.capacity() << endl;
    return 0;
}
Your imminent problem is that your code essentially does:
1
2
3
4
Foo* foo = new Foo;
Foo* bar = foo;
delete bar;
assert( foo == nullptr ); // failure 


PS: Raw pointers in a vector ... you should consider alternatives.
Topic archived. No new replies allowed.