How to remove an element from a dynamically allocated array of objects with operator -= without using std::vectors?

StackOverflow https://stackoverflow.com/questions/18508963

Question

Overloading the operator -=:

RentACar& operator-=(const Automobile& av)

In RentACar i have a dynamically allocated array of Automobile *a

So lets say that if any a has the same a.brand with av.brand then that a should be removed and the allocated memory freed for one object.

I thought sth. like if it doesnt find an object with the same brand it return *this, but if it does, it allocates space for a new automobile array of size of a-1, assigns objects of, skips the one with the same brand, but i dont know how to write it.

I don't know how to write with vectors and push back, anyway, i study for an exam and we never used vectors for whatever reason so i can't use them on the exam so i must do this even if it is a stupid implementation!

Thanks!

Was it helpful?

Solution

First, you have to find the object you want to remove: std::find_if is good for this, but if it is classwork, they may expect you to write your own implementation of a linear search. Once you've found the entry, you delete the pointer, and either set it to null (and ensure that all other logic works correctly when there are null pointers in the array), or shift all of the following entries down one. (std::copy could be used for the shift.) Of course, if you shift, you'll also have to keep track of where the valid entries in the array end.

There's not really any reason to create a new array when removing objects. Just keep track of the logical end of the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top