Erasing a specific element in a vector

In this portion of code I am setting an iterator, initializing it to the beginning and then setting it to variable of type int to remove the integer or atleast this is what I believed I was doing. In reality, it's just removing the beginning element of my vector. For example, say my vector is 5,6,7 and I enter 7 to remove it automatically removes 5. How would I erase a specific element. I'm guessing the problem is with my iterator initialization.

1
2
3
4
5
6
7
	vector<int>::iterator toRemove=v.begin();
	int x = *toRemove;
	cout<<"Number to remove"<<endl;
	for(int i=0; i>v.size(); i);
	cin >> x;

	v.erase(toRemove);
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.";
}
After I posted this I actually looked at that loop and wondered why I had had that in there... but thank you so much for the help! Much appreciated!
Topic archived. No new replies allowed.