Search code examples
c++algorithmvectorerase

C++: Using remove_if to filter vector on a condition


What is the correct syntax to use erase+remove_if to remove all elements in a vector, that are smaller than a specific value. However, this specific value is not a constant, but a variable.

Refer to the code to get a better understanding of the question:

for (int i = 0; i < arr.size(); i++)
{
    int currEle = arr[i];

    /*
        How do I use erase + remove_if to remove the elements from arr that
        are smaller than currEle? 
    */

}

Solution

  • Below example demonstrates the usage of erase-remove_if. limit is captured by reference and can thus be modified outside the lambda:

    #include <vector>
    #include <algorithm>
    #include <iostream>
    int main()
    {
        std::vector<int> vec{0,1,2,3,4,5,6,7,8,9};
        int size = vec.size();
        for (int limit = 0; limit <= size; limit++)
        {
            vec.erase(std::remove_if(std::begin(vec), std::end(vec), [&limit](int i) {
                return i < limit;
            }), std::end(vec));
            for (auto& v : vec)
                std::cout << v;
            std::cout << std::endl;
        }
        return 0;
    }
    

    Expected output:

    0123456789
    123456789
    23456789
    3456789
    456789
    56789
    6789
    789
    89
    9