Ordered removal of a Vector

May 7, 2016 at 8:57pm
I am trying to remove an element from a vector at a location given from the user.
I was successful at adding an element to my vector and preserving the order.
I know that ordered removal is the opposite of ordered insertion.
I was told by my instructor that the only difference is that the for loop in the function will shift the elements to the left and then do a pop_back.
Here is what I have for the ordered insertion:

1
2
3
4
5
6
7
8
9
10
void addValueOrdered(vector<int>& v, int loc, int val)
{
if(loc < 0 || loc > v.size()) return;
v.push_back(val);
for(int i = v.size() - 1; i < loc; i--)
{
v[i] = v[i - 1];
}
v[loc] = val;
}


I have tried time and time again to modify the different parts of this function to change it to a ordered removal function, but I'm lost.
I am not certain how to modify it.
Last edited on May 7, 2016 at 8:58pm
May 7, 2016 at 9:06pm
This is the closest I have gotten so far:

1
2
3
4
5
6
7
8
9
void deletionO(vector<int>& v, int loc)
{
    if(loc < 0 || loc > v.size()) return;
    for(int i = 0; i <= v.size(); i++ ) 
    {
        v[i] = v[i + 1];
    }
    v.pop_back();
}


It keeps the order, and deletes an element...
But it always deletes the element at location 0 and I am not sure how to make it delete the element at whatever location I choose
May 7, 2016 at 9:06pm
I am trying to remove an element from a vector at a location given from the user.


1
2
3
4
void removeElementAtLocation(vector<int>& v, int loc)
{
  v.erase(v.begin() + loc);
}

May 7, 2016 at 9:11pm
I'll try that function out, thank you.
I'm wondering if that function you provided will still maintain the order of the elements in the vector though?
I know it may not be ideal; but, I am curious...
Is there a way to do it with the for loop I have?
May 7, 2016 at 9:13pm
1
2
3
4
5
6
7
8
9
10
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();
}
May 7, 2016 at 9:35pm
Thank you so much!
I thought I was at least going in the right direction, just need 2 more changes lol
I appreciate your help =]
Topic archived. No new replies allowed.