std::remove#include <algorithm>() does not delete elements from a container but shifts the kept elements forward and leaves the rest with unspecified values (?). It returns an iterator to the new logical end:
std::vector#include <vector><int> v; // [1, 2, 1, 3]
std::vector#include <vector><int>::iterator end = std::remove#include <algorithm>(v.begin(), v.end(), 1);
v; // [2, 3, ?, ?]
v.size(); // 4
end; // Points to the element after 3.std::vector#include <vector><int> v = {1, 2, 1, 3};
auto end = std::remove#include <algorithm>(v.begin(), v.end(), 1);
v; // [2, 3, ?, ?]
v.size(); // 4
end; // Points to the element after 3.The new logical end iterator can be used with v.end() to discard the range of leftover elements:
v.erase(end, v.end());
v; // [2, 3]
v.size(); // 2std::remove_if#include <algorithm>() removes the elements matching a predicate instead of a value:
bool is_even(int x) {
return x % 2 == 0;
}
std::vector#include <vector><int> v; // [1, 2, 1, 3]
v.erase(std::remove_if#include <algorithm>(v.begin(), v.end(), is_even), v.end());
v; // [1, 1, 3]std::erase() and std::erase_if() perform the remove-erase idiom in one call and return the number of elements removed:
std::vector#include <vector><int> v = {1, 2, 1, 3};
std::erase(v, 1); // 2
std::erase_if(v, [](int x) { return x % 2 == 0; }); // 1
v; // [3]
v.size(); // 1
Dan