We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,055 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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

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

2
Contributors
2
Replies
1 Hour
Discussion Span
1 Year Ago
Last Updated
3
Views
Question
Answered
BryantFury
Light Poster
45 posts since Sep 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 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.

Ancient Dragon
Achieved Level 70
Team Colleague
32,128 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69

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.

BryantFury
Light Poster
45 posts since Sep 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 1 Year Ago by Ancient Dragon

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0636 seconds using 2.7MB