Help With Deleting Array Elements, thank you!

Hi, I am working on writing a code to delete numbers from an array taken from a list that I have generated (simply a list of integers). I am trying to get it so if I have a list such as 2,4,6,8,9 and I delete 8, that it will then output the list as 2,4,6,9.

This is for an introduction to C++ class that I am taking, but it is not a graded or assigned homework. It's an extra practice I requested from the professor but he won't be able to give feedback on it until after our next exam (and while I appreciate the extra practice, feedback at that point is useless to help study for the exam).

The part I am struggling with is the actual delete function, which is at around line 80. I have a main function, a bool function to open the file in question, a void function to read the data from the file, and a void function to print the data into the array. However, I am stuck on my void function for deleting an item.

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

#include <iostream>
#include <fstream>
using namespace std;

//constants
const int CAP = 100;

//function prototypes
bool openFile(ifstream &);
void readData(ifstream &, int [], int &);
void printData(const int [], int);
void deleteItem(int[], int &, int);


int main()
{
    ifstream inFile;
    int list[CAP], size = 0;
    
    if (!openFile(inFile))
    {
        cout << "Program terminating!! File not found!" << endl;
        return -1;
    }
    //read the data from the file
    readData(inFile, list, size);
    inFile.close();
    cout << "Data in file:" << endl;
    printData(list, size);
    //delete a few items
    deleteItem(list, size, 20);
    deleteItem(list, size, 210);
    deleteItem(list, size, 110);
    deleteItem(list, size, 220);
    printData(list, size);
    //end program
    cin.ignore(100, '\n');
    cout << "Press any key to continue...";
    getchar();
    
    return 0;
}

//function to open file
bool openFile(ifstream &inFile)
{
    inFile.open("numbers.txt");
    if (!inFile)
    {
        return false;
    }
    return true;
}

//reads the data from the file
void readData(ifstream &inFile, int list[], int &size)
{
    while (!inFile.eof())
    {
        inFile >> list[size++];
    }
}

//print the contents of the array
void printData(const int list[], int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << list[i] << endl;
    }
    cout << endl;
}


//delete an item (num) from the array
//if num is not found, will display 'Item Not Found'
void deleteItem(int list[], int &size, int num)
{
    int input;
    int index;
    cout << "Enter the number to delete: ";
    getline(cin, input);
    index = (input.c_str());
    if (index >= 0 && index < currentIndex) {
        for (int i = index; i < size -1; i++) {
            list[i] = list[i+1];
        }
        size--;
        cout << "Entry deleted." << endl;
    } else {
        cout << "Error. No valid entry to delete."  << endl;
    }
    return;
}


Any suggestions on how to go about this would be most appreciated! My issue is with the void deleteItem function (last function, around line 80). Thank you!
Last edited on
First of all... hi, welcome to C++ as taught by someone with no interest in teaching the best practices in C++. This is actually a problem that's made trivial if you were to use std::vector instead of C-style arrays. But, that doesn't help you, so...

Usually, what you'd do in this kind of situation to delete an element of an array of size s at index i would be to move each element down one position in your array (closer toward zero) from i+1 onward to s-1, then reduce your size variable by one after the fact. If you're unsure what I mean by "move", then you can just use normal assignment (=).

So, if we had an array that was 6 elements long, and you wanted to "delete" the value at a[3], what you'd do is move a[4] into a[3], then a[5] into a[4], then reduce your array's size variable from 6 to 5. You wouldn't, however, affect a[0], a[1], or a[2].

This particular problem also requires you to search your array. So, before doing the deletion, you'd check each element of your array until you find one matching num, then use that element's index for the deletion as described above.

It might actually help you to write two functions, one named findItem, and one named deleteAt, and call them both in deleteItem.

Does that give you a better idea of how to do it?

-Albatross
Last edited on
Thank you so much for responding, I appreciate it.

What you've written makes a lot of sense, in terms of moving each element closer towards zero (since 0 is the first in the array, 1 is the second...) however I'm not entirely sure how that would be actually implemented.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

void deleteItem(int list[], int &size, int num)
{
    int input;
    cout << "Enter the number to delete: ";
    cin >> input;
    if (input >= 0 && input < size) {
        for (int i = size; i < size -1; i++) {
            list[i] = list[i+1];
        }
        size--;
        cout << "Entry deleted." << endl;
    } else {
        cout << "Error. No valid entry to delete."  << endl;
    }
    return;


I've updated my code to what is above based on reading your suggestions, however whenever I enter a number to delete from the original text file, I get my error message "Error. No Valid Entry to Delete." even though that number is in my original file, so clearly I am doing something wrong since the program can't find the numbers in my original file.

Just for an example, my file data numbers in my "numbers.txt" file that I am using are:

20
25
30
100
110
120
130
200
210

For example, when I enter "200" into the "enter the number to delete:" field, I get the error message that I wrote stating that there is no valid entry to delete. However, if I enter "0" or "1" (the location in the array) then I can get the entry to delete. I am guessing this is a problem with searching the array for the actual integer, rather than just guessing what position the integer is in? Thank you for any suggestions.
Last edited on
That's part of why I suggested breaking it up into two functions: one to find the number 200, and another to delete the element at index 7.

What you have there is the deleteAt portion of what deleteItem needs to do: it takes an index, then shuffles everything over (good work on the loop on line 8, by the way). input, in this case, is the index you want to delete, not the value. Now you just need the bit of code that finds that element, then make that code search based on the value of num.

Also, to clarify: is deleteItem supposed to delete every instance of the specified item that it finds, or just the first?

-Albatross
First, let me congratulate you on nicely structured code. You have comments describing what you're doing, especially on the deleteItem() function.

There are a few problems with your code right now. First, the variable input in deleteItem is being treated as an index into the array, not a value in the array to delete. In other words, when you enter 200, it thinks you want to delete list[200], not "the value 200, wherever it occurs within the list."

Second, even if you enter an index instead of a value, the loop won't work:
for (int i = size; i < size -1; i++) {
First you assign i=size, then you check to see if i is less than size-1. That's false right from the start.

To delete the item at the index input. You have to start at input, and work your way up:
1
2
3
for (int i=input; i<size-1; ++i) {
    list[i] = list[i+1];
}


Now, let's get back to those fine comments you write for deleteItem:
1
2
//delete an item (num) from the array
//if num is not found, will display 'Item Not Found' 


Wait a sec. The comment says you're deleting num, but you prompt the user for some other number? What's up with that?

So you need three more changes (besides the one I mentioned):
1. Add code to find num within the array so you know which index to delete.
2. Modify the code to set input to the index where you found num.

Good luck, and again, nice job so far.
Thank you, yes that makes sense. I'm honestly really impressed someone actually responded at all, and am grateful for that - thanks again.

Do you have any suggestions for the findItem section? I understand in theory what you mean by the input being the array index that I want to delete (as opposed to a value, like 200). However I am stuck on what to do to make the program find a particular value (like 200), give its place in the array, and then subsequently delete that value.

For the clarification, I am working with a list compiled of all unique integers, so thus it would delete the first (but also only) instance of that integer.
@dhayden

You're right, my comments are not aligned with my definitions below. I've adapted it as follows based on your suggestions, is this what you meant?:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//delete an item (num) from the array
//if num is not found, display 'Item Not Found'
void deleteItem(int list[], int &size, int num)
{
    cout << "Enter the number to delete: ";
    cin >> num;
    if (num >= 0 && num < size) {
        for (int i = num; i < size -1; ++i) {
            list[i] = list[i+1];
        }
        size--;
        cout << "Entry deleted." << endl;
    } else {
        cout << "Error. Item not found. No valid entry to delete."  << endl;
    }
    return;
}


I'm unsure how to find the num within the array (as in, the integer, rather than the array position), do you have any suggestions for that?

Thank you again.
Apologies if I wasn't clear. Finding your desired element is actually the easy part. As a hint, all you need for a simple implementation is:
* one variable that's meant to store an index, initialized to some value that's not a valid index of your array
* one for loop
* one if statement (without a matching else statement)
* one comparison in the condition of that if statement
* some way of breaking out of the loop once you've found your matching element (after storing its index in the variable)

I hope that helps!

-Albatross

P.S. - This is usually a situation where we'd point you to std::find. For future reference, here's how you'd use it:
1
2
3
4
5
6
7
8
#include <algorithm>
//...
const int* result = std::find(list, list+size, desired);
if(result != list+size) {
    const int index = result-list;
} else {
    //Found nothing!
}


EDIT: Accidentally got some stuff switched around that would have been really bad.
Last edited on
Thank you for the clarifications! The std::find looks really useful - unfortunately we haven't gotten to the chapter with #include <algorithm> yet so I am going to hold off using that function but it seems a lot easier for use in the future.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//delete an item (num) from the array
//if num is not found, display 'Item Not Found'
void deleteItem(int list[], int &size, int num)
{
    for (int i = 0; i < size; ++i)
        {
            if (list[i] == num)
            {
                i = num;
            }
        }
    cout << "Enter the number to delete: ";
    cin >> num;
    if (num >= 0 && num < size) {
        for (int i = num; i < size -1; ++i) {
            list[i] = list[i+1];
        }
        size--;
        cout << "Entry deleted." << endl;
    } else {
        cout << "Error. Item not found. No valid entry to delete."  << endl;
    }
    return;
}


Is this what you meant by adding the part to find the desired element utilizing a for loop and an if statement?
Close! All you're missing is:
* one variable that's meant to store an index, initialized to some value that's not a valid index of your array (clarification: I meant outside of the for loop)
* some way of breaking out of the loop once you've found your matching element (after storing its index in the variable)

Side note, lines 12, 13, and 14 of that function are all going to need to be changed once you have that part of your code working as you want it to.

-Albatross
Hi Albatross, thank you again for the help. Do you mind to show me what you mean by initializing some variable to a value that's not a valid index of the array? (does it have to be a negative number then?)
I completely understand if you can't do this but I think what'd be most helpful for me is if you could show me what you mean within the confines of the code in my previous post.
Right, either negative, or greater than/equal to the size of the array. -1 is a commonly-used value for stuff like this.
1
2
3
int result_index = -1;
for(int i = 0; i < size; ++i) {
//... 


-Albatross
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

//delete an item (num) from the array
//if num is not found, display 'Item Not Found'
void deleteItem(int list[], int &size, int num)
{
    // search for num in array
    int resultIndex = -1;
    for (int i = 0; i < size; ++i)
        {
            if (list[i] == num)
            {
                num = resultIndex;
                break;
            }
        }
    cout << "Enter the number to delete: ";
    cin >> num;
    if (num >= 0 && num < size) {
        for (int i = num; i < size -1; ++i) {
            list[i] = list[i+1];
        }
        size--;
        cout << "Entry deleted." << endl;
    } else {
        cout << "Error. Item not found. No valid entry to delete."  << endl;
    }
    return;
}


Thank you, this is what I've gotten to now. Could you clarify what you meant by lines 12-14 will need to be changed? I'm sorry I'm struggling so much with this.
These lines:
1
2
cout << "Enter the number to delete: ";
cin >> num;


The line below those two (the one that was originally 14) might also need to be changed, depending on whether you're going to go through with changing the meaning of num or not. What do I mean by that? Well, at the top of deleteItem, num contains the value to search for. After the loop, however, it seems like you're using it to store the index of the element (which is what resultIndex was supposed to be for).

Relatedly, your loop is sadly not right: it effectively sets num to -1 if the previous value of num was found in your list. Then, when you hit line 18 (if (num >= 0 && num < size)), that condition will always be false.

Something that might help: try writing out comments for what each line of code should do. Try coming up with a clear idea of what each part of your code should do and what each variable should represent, and only then write out the code. You can delete the comments afterward, but each one should match up with a single line (or small block) of code.

An example of how that might look:
1
2
3
4
5
6
7
8
9
10
11
12
//delete an item (toFind) from the array
//if num is not found, display 'Item Not Found'
void deleteItem(int list[], int &size, int toFind) {
    int foundIndex = -1; //foundIndex might be a better name than resultIndex
    //Iterate over whole array.
        //If an element matches toFind, set foundIndex to its index and break.
    //If foundIndex is -1, print Item Not Found
    //Otherwise, delete the element, as follows:
        //Iterate from foundIndex to the second-to-last index.
            //Set the ith element to the i+1th element.
        //Decrease size by 1.
}


Hopefully that helps. Struggling at first is okay, so long as you stay willing to learn and work through it, right?

-Albatross
Thank you, that is very helpful.

I still don't think I get it completely but I really appreciate all your help and I am going to read through all your comments again to get more clarity.

And yes I agree, struggling is okay so long as perseverance prevails. Struggling does suck though...usually things are very intuitive to me so this is a challenge!
Last edited on
Is there any way you could show me what you mean by writing out an example code for the deleteItem section? If not, I completely understand as I know that takes a bunch of time but I'm at a loss here :(
Honestly? It wouldn't that long, but I have reservations about giving code solutions to people, because there's something of an incentive to take those solutions and run.

Tell you what. I'll meet you halfway. Here's a function that finds an item in a list, and returns the index.
1
2
3
4
5
6
7
int findItem(int list[], int size, int item)
{
    for(int i = 0; i < size; ++i) {
        if(list[i] == item) return i;
    }
    return -1;
}


It'll be your job to figure out how to either a) use this function in your code, or b) use the code in this function in your own function. Alright?

-Albatross
Yes, that is incredibly helpful - more than happy to meet you halfway there; thank you. I really appreciate you taking the time to answer all of my questions. You helping me through this code and what I've now learned really made my day, so thank you.

Going forward, I will definitely going to be utilizing your suggestion of writing out the comments for what each line of code should do prior to writing the code itself. I like how it gives you a good plan the entire program and breaks it into more manageable elements to put together. Thanks again Albatross.
Last edited on
Topic archived. No new replies allowed.