Line 1 is creating an iterator that points to the first element in your vector. So if you have "5,6,7", it points to the 5.
Line 2 creates a variable named 'x' and assigns it so that it contains the value that your iterator points to. Since your iterator points to 5, this means x=5. Though this value is never used, as you reassign x on line 5.
Line 3 prints a statement to the user
Line 4 is an incorrectly formed loop that effectively does nothing.
Line 5 gets an integer from the user and assigns that value to x. So if the user inputs 7... then x=7. Note that
this does not change your iterator since 'x' and your iterator are two completely different variables.
Line 7 erases whatever element 'toRemove' points to. Since it still points to 5 (you never changed it), this will remove the 5, leaving "6,7" in the vector.
How would I erase a specific element |
You need to search your vector for a specific element and obtain an iterator to that element. Then you can call erase with that iterator.
The <algorithm> header provides a 'find' function which you can use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
cout << "enter a value to remove: "; // print message to user
int x;
cin >> x; // get the value they want to remove, put it in 'x'
auto iter = std::find( v.begin(), v.end(), x ); // search 'v' for 'x', returns an iterator
if(iter != v.end()) // make sure at least 1 element was found
{
v.erase(iter); // erase that element
}
else
{
cout << "Value of " << x << " was not found in the vector.";
}
|