How to delete an object from heap allocated array

I am a beginner, and I want to delete an item from an array, non-STL.

This doesn't seem possible? Below. So, out of share curiosity, how can I delete or remove an item from a regular array, I am not using STL. I want to know how this can be done with one dynamic array that's been allocated on the HEAP.

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
52

#include <iostream>
#include <string>

class Monster{
public:
  Monster(){};
  Monster(std::string name) : name(name){}
private:
  std::string name = "";
};

class Monsters{
public:
  Monsters(int max):max(max){
    monsters = new Monster[max];
  }

  void add(const Monster* m){
    monsters[total++] = *m;
  }

  void remove(const Monster* m)
  {
    for(Monster* mptr = monsters; mptr!=monsters+total; mptr++){
      if(mptr == m){
        delete mptr;
      }
    }
  }

private:
  Monster* monsters = nullptr;
  int max = 0;
  int total = 0;
};

int main()
{
	int size = 5;
	Monsters* monsters = new Monsters(size);
	Monster* monster1 = new Monster("Sally");
  Monster* monster2 = new Monster("Rich");

  monsters->add(monster1);
  monsters->add(monster2);

  monsters->remove(monster1);

   return 0;
}
Last edited on
There are two ways.

If the ordering is not important, find the index of the item to be deleted, swap it with the last element and decrement the item count. This is the fastest method and it's performance doesn't depend upon how many items in the dynamic array.

If the ordering is important, find the index of the item to be deleted, shuffle all elements after this down one to overwrite the item to be deleted and decrement the item count. This is the slowest method and performance depends upon how many items exist after the item to be deleted.
There are two ways.

If the ordering is not important, find the index of the item to be deleted, swap it with the last element and decrement the item count. This is the fastest method and it's performance doesn't depend upon how many items in the dynamic array.

If the ordering is important, find the index of the item to be deleted, shuffle all elements after this down one to overwrite the item to be deleted and decrement the item count. This is the slowest method and performance depends upon how many items exist after the item to be deleted.


The order doesn't matter much!
See the way it's done in your other post at http://www.cplusplus.com/forum/beginner/273117/
See the way it's done in your other post at http://www.cplusplus.com/forum/beginner/273117/


That doesn't help. Sorry!
Object* o = new Object[size];
`o[i]' is an `Object', it is not a pointer

Object** o = new Object*[size];
now `o[i]' is a pointer
Topic archived. No new replies allowed.