Search code examples
c++vectorlambdaremove-if

incorrect lambda usage in remove_if


so I have a vector holding vectors like so:

vector<vector<int>> vec;

And I am trying to use a comparator (pred) to iterate through the vectors within vec and determine which vectors get deleted by remove_if and erase. My code so far is as follows:

vector<vector<int>> deleted_vecs;    

vec.erase(remove_if(vec.begin(), vec.end(),
                               ([vec, pred](vector<int> x) {
                                 if (pred(x)) {
                                     return true;
                                 }
                                 else {
                                     deleted_vecs.push_back(x);
                                     return false;
                                 }
                               },
                               vec.end())));

Is there something wrong I am doing syntax-wise here?

My compiler errors are on the lines "if (pred(x))" and "deleted_vecs.push_back(x);" and say there is no matching function call to pred and push_back, although my predicate is specifically intended to take in a vector and I've declared deleted_vecs as a vector>. This leads me to think it is a problem with how I've declared x, but I'm not sure.

Any help would be appreciated!


Solution

  • You have an error with the parentheses as well as with the capture list.

    You are capturing the used variables by value, which ends up in copying the objects. Try to capture the variables by reference, rather than by value. see http://en.cppreference.com/w/cpp/language/lambda

    For example:

     vec.erase(
        std::remove_if(vec.begin(), vec.end(),
        [&](std::vector<int> x) {
          if (pred(x)) {
            return true;
          }
          else {
            deleted_vecs.push_back(x);
            return false;
          }
        }),
        vec.end());