0

I want to remove all element that are greater than 4 and this program prints : 4 3 1 8 1 and is not correct

std::vector<int> arr1 = { 4, 6, 3, 8, 1 };
std::remove_if(arr1.begin(), arr1.end(), [](int i) {return i>4; });
    print(arr1);

What am i doing wrong?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Ac1234
  • 67
  • 6

1 Answers1

3

std::remove_if doesn't actually erase any elements. It only moves the elements to be retained to the front of the vector, and returns an iterator to the first element to be removed. (This applies to any contiguous container, not just vector).

You need to then call std::vector::erase from that iterator to the end of the vector to actually erase the elements that have been removed from arr1:

auto last = std::remove_if(arr1.begin(), arr1.end(), [](int i) {return i>4; });
arr.erase(last, arr.end());
cigien
  • 57,834
  • 11
  • 73
  • 112
  • 1
    It doesn’t move elements to the end of the vector. It leaves whatever is at the end alone, and returns an iterator that points at the end of the sequence that results from removing elements that pass the test. Algorithms don’t know about containers; they operate on sequences. Anything after the end of the output sequence `[arr.begin(), last)` is junk. – Pete Becker Sep 17 '20 at 21:57