How to remove a vector element based on value?

I'm creating a custom CD collector and upon the user selecting the option to remove an existing CD, I'm a little unsure on how to remove it from the vector itself.

If I use the erase member function of the vector object it only removes the values/literals contained within the element, not the element itself. I'm aware of the invalidation that could occur afterwards.

Is their a way to remove an element in the vector based upon a value?

Any help is greatly appreciated, thanks. :)

1
2
3
4
5
6
7
  iter = find(cdEntries.begin(), cdEntries.end(), cdTitle);
	if (iter != cdEntries.end()) {
		iter->erase(); // This doesn't remove the element itself.
	}
	else{
		cout << "No entry found.\n" << endl;
	}
Last edited on
1
2
3
4
iter = std::remove(cdEntries.begin(), cdEntries.end(), cdTitle);
if (iter == cdEntries.end())
    cout << "No entry found.\n" << endl;
cdEntries.erase(iter, cdEntries.end());

Or simply
1
2
cdEntries.erase(std::remove(cdEntries.begin(), cdEntries.end(), cdTitle), 
                cdEntries.end());


Note that this approach will remove all CDs with given title.

Or you can update your current code replacing iter->erase(); with cdEntries.erase(iter);
Last edited on
Thanks for helping me with that, that makes so much more sense.

<3
Topic archived. No new replies allowed.