0
#include <iterator>
#include <vector>
#include <algorithm>

int removeLessThan(std::vector<int>& v, int limit) {
  std::remove_if(v.begin(), v.end(), [limit](int a){return a < limit;});
  return EXIT_SUCCESS;
}

My output:

Vector after removing all values under 44: [ 28 43 40 42 8 24 12 25 31 13 36 30 28 35 37]

Desired output:

Vector after removing all values under 44: [ ]

So why does my code not remove any elements when it should remove everything?

2 Answers2

5

why does my code not remove any elements when it should remove everything?

Actually, std::remove moves at beginning of the range all elements which don't satisfy predicate, AND returns iterator of the new end.

So usage is erase-remove idiom:

v.erase(std::remove_if(v.begin(), v.end(), [limit](int a){return a < limit;}),
        v.end());

In c++20, it can be simplified thanks to std::erase_if:

std::erase_if(v, [limit](int a){return a < limit;});
Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

The name of std::remove/std::remove_if functions are somewhat misleading in fact. They don't remove anything and should have named rather something like shift_if, because these functions just shift elements inside of the container and return past-the-end iterator for the new range of values. So you are supposed to erase these elements yourself:

v.erase(std::remove_if(v.begin(), v.end(), [limit](int a){return a < limit;}), v.end());
The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49