1,105,310 Community Members

How to delete an an object/element/thing from an array?

Member Avatar
BryantFury
Light Poster
45 posts since Sep 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have the following simple code. It consists of an array with 4 items. It first displays the items, then asks the user to delete as many as they want.(with an option to continue without deleting anything). After the user has removed or not removed items, the program will display the new update list.

i do not know how to delete specific things from my array. this is the code: (it works until you delete something, if you choose to not delete anything it works fine)

#include <iostream>
#include <string>
using namespace std;
class test
{
          public:
             int del;
             string word;
             void one(test array[]);
             };

void test::one(test array[]){
     array[0].word="0 cat";
     array[1].word="1 dog";
     array[2].word="2 bird";
     array[3].word="3 fish";
     for(int i=0; i<4; i++){
cout<<array[i].word<<endl;
     }
     cout<<"DELETE NOW. input 4 to confirm/finish"<<endl;
     for(int i=0; i<3; i++){
             cin>>del;
             if(del==4)
             break;
             delete &array[del].word;
     }

         for(int i=0; i<4; i++){
cout<<array[i].word<<endl;
     } 

}
int main(){
    test array[10];
    test tes;
    tes.one(array);
    system("pause");
    return 0;
}

any help is greatly appreciated

Member Avatar
Ancient Dragon
Achieved Level 70
27,573 posts since Aug 2005
Reputation Points: 5,231 [?]
Q&As Helped to Solve: 3,028 [?]
Skill Endorsements: 115 [?]
Team Colleague
Featured
Sponsor
 
0
 

You can't actually delete an element from the array. All you can do is mark it as an unused element. There are numerous ways to do that and it doesn't really matter which one you use as long as your program recognizes the element as being unused. For example, in the array you posted you could just set the word element of the array to an empty string, then when displaying all elements of the array if word is empty then just ignore it and move on to the next element.

Member Avatar
BryantFury
Light Poster
45 posts since Sep 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

alright so ive set it so you can choose what to "delete". But in the code ive actually set it to 10 arrays ahead (so it becomes invisible) theres an ugly blank spot but its minor i guess. thanks for helping.

Question Answered as of 2 Years Ago by Ancient Dragon
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article