Duplication after removing one element from structurre array

I am trying to remove an element from an array of structure records.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 cout<<"Choose a student to delete:";
    cin>>input;
    
  if(input==subjects[choice].stuCount)
    {
        subjects[choice].stuCount-=1;                   //special case if user   wants to remove the last element
        return;
    }
    for(int q=input;q<(subjects[choice].stuCount);q++)            //input starts updating values from the chosen option with it's next counterpart till the end
    {
        strcpy(students[choice][input].ID,students[choice][input+1].ID);
        strcpy(students[choice][input].name,students[choice][input+1].name);
        students[choice][input].marks=students[choice][input+1].marks;
    }
    subjects[choice].stuCount-=1;     */Remove one from the array*/
    return;


//
Original:
J46378 Melvin Wong 56
J33324 Alexander Yu 23
J77409 Suzy Leq 55
J99373 Catherine Ng 66


Say, I intend to delete Alexander;
After the code:
J46378 Melvin Wong 56
J77409 Suzy Leq 55
J77409 Suzy Leq 55 //Both alexander and Catherine is gone...



However, after the code, the element I intend to be deleted is deleted all right, but the subsequent record after the deleted point is duplicated and thus occupies 2 spaces, as such the last element from the original records just vanished.

Any ideas about this, fellow programmers?Thanks in advance.
Last edited on
Have you considered using std::vector instead of the array and std::string instead of the C-strings?

The easiest way to "delete" an item in a C style array would be to copy the last element into the element to be "deleted" then reduce the "size" of the array by one.

I am afraid my lecturer hasn't touched on the topic about vectors yet.. Plus I did copy the array into the front after deleting it and reducing the size with (subject[choice].stuCount -1) but it isn't working for some reason..Thanks for the reply though/
closed account (48T7M4Gy)
Plus I did copy the array into the front after deleting it


Well that's not the way to do it. Follow jlb's suggestion :)

1. copy the last element into the element to be "deleted"
2. reduce the "size" of the array by one.

Another way, common to databases, is to change one of the attributes eg ID to "deleted" or -9 or something and ignore that object in future processing. Then have a 'clean' process to rebuild the array every now and again as a maintainence routine.
Topic archived. No new replies allowed.