How to Remove an Item from a Stl Vector With a Certain Value

C++ Erase vector element by value rather than by position?

How about std::remove() instead:

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

This combination is also known as the erase-remove idiom.

How do I remove an item from a stl vector with a certain value?

std::remove does not actually erase elements from the container: it moves the elements to be removed to the end of the container, and returns the new end iterator which can be passed to container_type::erase to do the actual removal of the extra elements that are now at the end of the container:

std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());

Remove an element from a vector by value - C++

You could use the Erase-remove idiom for std::vector

Quote:

std::vector<int> v; 
// fill it up somehow
v.erase(std::remove(v.begin(), v.end(), 99), v.end());
// really remove all elements with value 99

Or, if you're sure, that it is unique, just iterate through the vector and erase the found element. Something like:

for( std::vector<T>::iterator iter = v.begin(); iter != v.end(); ++iter )
{
if( *iter == VALUE )
{
v.erase( iter );
break;
}
}

std::vector removing elements which fulfill some conditions

std::remove_if comes to the rescue!

99 would be replaced by UnaryPredicate that would filter your delays, which I am going to use a lambda function for.

And here's the example:

v.erase(std::remove_if(
v.begin(), v.end(),
[](const int& x) {
return x > 10; // put your condition here
}), v.end());

C++ Remove element from vector by value

std::remove is only available if you include header <algorithm>.

This is clearly stated by the MSDN documentation here as well as any C++ reference.

How to remove element from vector by value but only single instance of that value?

You may use:

v.erase(v.begin() + std::max(index1, index2));
v.erase(v.begin() + std::min(index1, index2));

or even

auto indexes = std::minmax(index1, index2);
v.erase(v.begin() + indexes.second);
v.erase(v.begin() + indexes.first);

How do I erase an element from std::vector by index?

To delete a single element, you could do:

std::vector<int> vec;

vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);

// Deletes the second element (vec[1])
vec.erase(std::next(vec.begin()));

Or, to delete more than one element at once:

// Deletes the second through third elements (vec[1], vec[2])
vec.erase(std::next(vec.begin(), 1), std::next(vec.begin(), 3));


Related Topics



Leave a reply



Submit