how to delete element in an array

Oct 26, 2017 at 11:22pm
The user will input a number from the array that they want removed. How would I do that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  else if (input == 5){
        int entry = 0;
        cout << "Enter a number" << endl;
        cin >> entry;
        
        
        for (int i = 0; i < cnt; i++){
            
            if(array[i] == entry){
                
                    }
            else if (array[i]!= entry){
                cout << entry << " does not exist" << endl;
            }
        }}
Oct 27, 2017 at 1:15am
I recommend using std::vector for this. Arrays sizes are determined and unchangeable upon compile. Vectors are very dynamic and customizable. If you have to use an array I would suggest copying over the array with the selected value removed from it, but the array size will still have to be the same.
Oct 27, 2017 at 1:16pm
1) you could make the array data type a struct or class with a 'is deleted' field.
2) if the data is not sorted, you can swap the deleted guy with the last guy and -- the current size of the container.
3) if the data is sorted, you can do a memmove or similar routine (very inefficient) to shuffle the data internally to close the gap.
4) similar to #1 you can keep a side by side array of bool on what locations are in use.


As already said you can use vector which is the better approach. #2 very good. The others are clunky.
Topic archived. No new replies allowed.