Code fix for std::remove_if example
eugenefil opened this issue · comments
Evgeniy Filimonov commented
std::remove and std::remove_if remove elements logically, i.e. vector size is unchanged after removal. Removal must be finished with vector.erase(). This is Erase-remove idiom.
On p.60 in 17.Iterators_Containers_Alg.pdf under title "Example":
#include <cstdlib> // std::rand
+#include <numeric> // std::accumulate
struct Unary {
- bool operator()(int value) {
- return value > 100;
- }
+ bool operator()(int value) { return value > 100; }
};
int main() {
std::vector<int> vector { 7, 2, 9, 4 };
-
int product = std::accumulate(vector.begin(), vector.end(), // product = 504
1, std::multiplies<int>());
- std::srand(0);
std::generate(vector.begin(), vector.end(), std::rand);
// now vector has 4 random values
- std::remove_if(vector.begin(), vector.end(), Unary());
-} // remove all values > 100
+ // remove all values > 100 using Erase-remove idiom
+ auto new_end = std::remove_if(vector.begin(), vector.end(), Unary());
+ // elements are removed, but vector size is still unchanged
+ vector.erase(new_end, vector.end()); // shrink vector to finish removal
+}
- include for std::accumulate
- operator() is squeezed to preserve original line count
- std::srand(0) makes no big difference, removed to preserve original line count
- add call to vector.erase() to actually remove elements