federico-busato / Modern-CPP-Programming

Modern C++ Programming Course (C++03/11/14/17/20/23/26)

Home Page:https://federico-busato.github.io/Modern-CPP-Programming/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Code fix for std::remove_if example

eugenefil opened this issue · comments

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
+}
  1. include for std::accumulate
  2. operator() is squeezed to preserve original line count
  3. std::srand(0) makes no big difference, removed to preserve original line count
  4. add call to vector.erase() to actually remove elements