I’ve been trying to erase an element from an array without changing the index order, for instance:
class MyObject
{
int id;
public:
MyObject() { }
void setId( int i ) { id = i; }
void showId() { std::cout << "ID: "<< id << "\n"; }
};
MyObject *myArray;
int main ( )
{
myArray = new myArray[6];
for( int i = 0; i < 6; i++ )
{
myArray[i]->setId(i);
myArray[i]->showId();
}
}
I want to remove myArray[3] without changing the index of the others. e.g:
myArray[0] = ID: 1
myArray[1] = ID: 2
myArray[2] = nothing
myArray[3] = ID: 4
myArray[4] = ID: 5
myArray[5] = ID: 6
I’ve tried to use use memset(), but it didn’t work.
memset(&myArray[3],0,sizeof(MyObject));
You are calling
memsetto write a bunch of zeros over the top of an object instance. Do not do this! You may get away with it if your class is a true POD class. You might end up just setting the ID to 0. But maybe there is more to your class that you aren’t showing. In anycase, even if it isn’t POD, don’t usememsetlike that.You can either store pointers to object and use the null pointer to indicate there is nothing there. I’d do this with
std::vector<MyObject*>. Or you use a sentinel object instance, for example with ID of -1.The other thing that could be a problem is that you appear to be using 1-based indices. C++ arrays are 0-based, so the first element is
myArray[0]and notmyArray[1].