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.
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
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?