Search code examples
c++vectorlambdatypedef

typedef vector of functions as a function parameter


I have to write a function that receives std::vector<int> as the first argument, and a vector of functions that will be applied over each element in the vector. If the element does not meet the criteria of all predicate functions, in that case I have to replace that element with the default third argument that the function receives, which has a value of -1. If any predicate function returns false, that element should be replaced with the default argument.

This is what I've written so far:

#include <iostream>
#include <vector>
#include <functional>

typedef std::vector<std::function<bool(int)>> Functions;

void default_if_not_all(std::vector<int>& i, Functions f,int def=-1){
  for(auto& num : i){
    for(auto& fun : f){
      if(!(fun(num))){
        num=def;
      }
    }
  }
}

int main(){

  std::vector<int> v{1,2,3,4,5};

  Functions f{
    [&](int a){if( a>0 )return 1;},
    [&](int a){if (a%2==0) return 1;}
  };

  for(const auto& e : v){
    std::cout<<e<<" ";
  }

  std::cout<<std::endl;
}

The problem is that I am not sure how to call the functions from the vector of functions in the right way so that I can change the value of the elements in the int vector.

Does anyone have some advice how to use typedef Functions properly in this case? Am I on the right track?


Solution

  • Your lambda functions only return a value in the true case. You need to return false too.

    You don't need if for that. Just return the result of the comparison:

    // note: the lambda capture isn't really needed since it's not used
    Functions f{[&](int a) { return a > 0; },
                [&](int a) { return a % 2 == 0; }};
    

    You also need to call your default_if_not_all afterwards:

    default_if_not_all(v, f);
    

    Demo