F100
F100

Reputation: 11

Delete a record in an array

int i;
int Input;

cin >> Input;

 for(i = 0; i < Size ; i ++ )
  if (List[i].PersonID == Input) {

 }

I am trying to make a function that deletes a record from the array based on the id input provided. I am not sure what to do beyond this here. Will I also need to shift the values in the array after a record is removed?

Upvotes: 1

Views: 1166

Answers (4)

user379888
user379888

Reputation:

int i;

int Input;

cin >> Input;

 for(i = 0; i < Size ; i ++ )
 {
   if (List[i].PersonID == Input)
   {
    for(int j=i;j<size-1;j++)
    {
     List[j]=List[j+1];
    }
 }
 }

Upvotes: 0

6502
6502

Reputation: 114461

I think the best way to remove elements from an array/vector is to use a copy approach with something like:

int write_ptr = 0;
for (int read_ptr=0; read_ptr < n; read_ptr++)
{
    if (... keep element array[write_ptr] ? ...)
    {
        if (read_ptr != write_ptr)
            array[write_ptr] = array[read_ptr];
        write_ptr++;
    }
}
// The new size of the array is write_ptr

This will allow to remove even multiple elements with just one pass.

The standard library includes this approach as std::remove_if, however until C++0X arrives it's annoying to use because of limitations of the language (the code needed to be able to specify the test becomes easily quite ugly).

Upvotes: 0

wilhelmtell
wilhelmtell

Reputation: 58667

Here I'm assuming List is a primitive array of ints.

#include<algorithm>  // where std::remove() resides
#include<iterator>   // where std::distance() resides (not strictly necessary)

struct BadPerson {
    BadPerson(int Bad) : Bad_(Bad) { }
    bool operator()(const Element& Elem) const {
        return Elem.PersonID == Bad_;
    }
};

// ...
int *NewEnd = std::remove_if(List, List + ListLength, BadPerson);

// the list now has a new end, because elements were "removed".
// but they weren't really removed; the array still has the same fixed size.
int ListLength = std::distance(List, NewEnd);

Upvotes: 1

santiagoIT
santiagoIT

Reputation: 9431

I can't tell what type your List is. But you should go for something like this:

List.RemoveAt(i--);
List.DeleteAt(i--);

i-- will decrement i AFTER the function has been called.

You should not need to shift any values in the array if you are using the standard containers. If you are responsible for the array, then you do need to shift your values.

** EDIT

Here is a link to an introduction to the standard containers. If you are managing your own dynamic array you should consider using these instead.

Upvotes: 1

Related Questions