Delete a number given by user in a vector

For this program I would like any instance of a given number to be deleted from my vector while still maintaining the order of the vector.
I have successfully been able to delete any element from a location given by the user but I am having trouble figuring out how to delete any instance of the given number.
I am not sure if I have to modify my function to shift over multiple times if the given number comes up multiple times
Any help would be greatly appreciated!
Here is what I have so far:
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
#include <cstdlib>
#include <iostream> 
#include <vector>

using namespace std;

vector <int> create(int size);
void storeRandom(vector<int> & );
void output (const vector<int> &);
void deletionO(vector<int>& v, int loc);
void removeVal(vector<int>& v, int val);

int main(int argc, char** argv) {

    srand(time(0));
    //Vector function
    cout << "Creating vector: " << endl;
    vector<int> v = create(10);
    cout << "Storing values in vector: " << endl;
    storeRandom(v); 
    cout << "Outputting vector: " << endl;
    output(v);
    
    //Delete element from given location in vector
    cout << "Please enter the value you'd like to delete from the vector: ";
    int val;
    cin >> val;
    removeVal(v, val);
    output(v);
    
    return 0;
}

/**
 * Creates and returns a vector of the given size with all 0's.
 * @param size
 * @return 
 */
vector<int> create(int size)
{
    vector<int> newVector;
    
    for(int i = 0; i < size; i++)
    {
        newVector.push_back(0);
    }
    return newVector;
}
/**
 * Function stores random values between 0 - 100
 * @param v
 */
void storeRandom(vector<int>& v)
{
    for(int i = 0; i < v.size(); i++)
    {
        v[i] = rand() % 11;
    }
}
/**
 * Outputs a vector in horizontal format 
 * @param v
 */
void output(const vector<int>& v)
{
    for(int i = 0; i < v.size(); i++)
    {
        cout << v[i] << "  ";
    }
    cout << endl;
}

void deletionO(vector<int>& v, int loc)
{
    if(loc < 0 || loc > v.size()) return;
    for(int i = loc; i <= v.size() - 1; i++ ) 
    {
        v[i] = v[i + 1];
    }
    v.pop_back();
}

void removeVal(vector<int>& v, int val)
{
    for(int i = 0; i < v.size(); i++)
    {
        if(v[i] == val)
        {
            deletionO(v, val);
        }
    }
}


I know my funtions aren't working correctly, I have just been tinkering with ideas as to how to make this work.
The std::vector class can delete an item for you:

v.erase( v.find( val ) );

Hope this helps.
Thank you so much, I also would like to figure out how to do this with an array. I'm guessing I wouldn't be able to do that with an array as well. So far all I know is that I can swap elements in my array and then change my size variable; but, when I try to use swap I can't seem to keep it ordered. Would swap be the best way to go about doing this in an array?
I'll go ahead and work with what you gave me and post the results; Again, Thank you =]

Edit: my IDE is not recognizing v.find
I'm looking up the v.erase function and trying to figure it out
Last edited on
Sorry for the double post but I have tried a couple different ideas and I'm not sure what to do.
I modified my removal function and it deleted two instances of the value I entered, it kept the same order too; but, I am not sure why it didn't delete the third instance of that number?
1
2
3
4
5
6
7
8
9
10
void removeVal(vector<int>& v, int val)
{
    for(int i = 0; i < v.size(); i++)
    {
        if(v[i] == val)
        {
           v.erase(v.begin()+val);
        }
    }
}

Here is the output I got from this:
1
2
3
4
5
6
Creating vector: 
Storing values in vector: 
Outputting vector: 
10  1  1  2  6  0  0  1  8  3  
Please enter the value you'd like to delete from the vector: 1
10  2  6  0  0  1  8  3   
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
#include <vector>
#include <algorithm>

// delete all instances of a given number,
// retaining the relative order of the remaining numbers
// returns the new size of the vector
std::size_t remove_val( std::vector<int>& seq, int value )
{
    // step 1. move all occurrences of value to the back of the vector
    // http://en.cppreference.com/w/cpp/algorithm/remove
    // returns an iterator to the one-past-the-last element to be retained
    const auto iter = std::remove( seq.begin(), seq.end(), value ) ;

    // step 2. remove all elements starting with iter, up to the end
    seq.erase( iter, seq.end() ) ;

    // or erase-remove idiom in a single step
    // seq.erase( std::remove( seq.begin(), seq.end(), value ), seq.end() );

    return seq.size() ;
}

// I also would like to figure out how to do this with an array.
// returns the new logical size of the array
std::size_t remove_val( int* seq, std::size_t num_elements, int value )
{
    if( seq == nullptr ) return 0 ;
    const int* ptr = std::remove( seq, seq+num_elements, value ) ;
    return ptr - seq ;
}

http://coliru.stacked-crooked.com/a/ad642cf039218882


> my IDE is not recognizing v.find

std::find()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// remove the first instance of a given number,
// retaining the relative order of the remaining numbers
// return true if an instance was removed
bool remove_first( std::vector<int>& seq, int value )
{
    // step 1. try to find the first occurrence of value
    // http://en.cppreference.com/w/cpp/algorithm/find
    const auto iter = std::find( seq.begin(), seq.end(), value ) ;

    if( iter != seq.end() ) // step 2. if an occurrence was found (this check is required)
    {
        seq.erase(iter) ; // step 3. remove it from the sequence
        return true ;
    }

    else return false ; // not found
}
void removeVal(vector<int>& v, int val)
{
for(int i = 0; i < v.size(); i++)
{
if(v[i] == val)
{
deletionO(v, i);
removeVal(v,val);
break;
}
}
}

try
my IDE is not recognizing v.find

Sorry. I've been using strings a lot lately. Thanks to JLBorges for pointing out that it is a standard algorithm.

This is what I always get for typing something blithely off the top of my head — it's invariably wrong...


I also would like to figure out how to do this with an array.

You can't actually move stuff in an array, only copy values around. Use a simple loop to copy stuff one element over, left-to-right:
  +---+---+---+---+---+---+---+---+---+---+---+---+
  | a | b | c | d | e | X | f | g | h | i | j | k |
  +---+---+---+---+---+---+---+---+---+---+---+---+
                           /   /   /   /   /   /
                          /   /   /   /   /   /
                         /   /   /   /   /   /
  +---+---+---+---+---+---+---+---+---+---+---+---+
  | a | b | c | d | e | f | g | h | i | j | k | k |
  +---+---+---+---+---+---+---+---+---+---+---+---+

Hope this helps.
Last edited on
Thank you everyone for their input.
JLBorges I have yet to learn algorithms but I am curious as to how to make this work with an algorithm. Thank you, I will be working with that method and learning it. I'll be attempting this problem with arrays using algorithms

This fixed my program, it deletes every instance of a given number now.
Thank you
The only part that confuses me is using a break in the for loop, I thought breaks were only used for menus in switch case?
1
2
3
4
5
6
7
8
9
10
11
12
void removeVal(vector<int>& v, int val)
{
for(int i = 0; i < v.size(); i++)
{
if(v[i] == val)
{
deletionO(v, i);
removeVal(v,val);
break;
}
}
}


Now that I have this working for my vector I'll look into making it work with an array, Thank you Duoas for that diagram. I'm not sure how I'll set up my loop but seeing the array like that will help me. After seeing that diagram though I am wondering if my code would have to be different to handle more than one instance of the given element to removed?

I've been working with the algorithms and haven't had much luck, I'm wondering if I can do this with my array similar to what I did with the vector.
I have an additional variable of size in my array function
I want it to iterate through all the elements of the array, find which elements are equal to the given number. Then remove them and shift over the remaining elements in order.
That last bit is what is giving me trouble; shifting the elements over.
This is about as far as i got on making a function for it:
1
2
3
4
5
6
7
8
9
10
void removeNum(int a[], int size, int num)
{
    for(int i = 0; i < size; i++)
    {
        if(a[i] == num)
        {
            //I know I have to do a size--; after I figure out how to move around the elements correctly. 
        }
    }
}
> That last bit is what is giving me trouble; shifting the elements over.

Divide and conquer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// move elements from position 'from' onwards by one position to the left
void move_left( int* array, std::size_t sz, std::size_t from )
{
    if( from == 0 ) ++from ; // defensive: just discard the element at position zero
    for( ; from < sz ; ++from ) array[from-1] = array[from] ;
}

// remove all elements equal to value, return new size
std::size_t remove_value( int* array, std::size_t sz, int value )
{
    for( std::size_t pos = 0 ; pos < sz ; )
    {
        // note: postfix decrement sz--
        // if elements are moved to the left, stay at the same position
        if( array[pos] == value ) move_left( array, sz--, pos+1 ) ;
        else ++pos ; // otherwise, move on to the next position
    }

    return sz ;
}

http://coliru.stacked-crooked.com/a/d8a9b099ddc52e95
Topic archived. No new replies allowed.