Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::find_if() with a comparison function that takes multiple input parameters

Tags:

c++

vector

I'm trying to use the std::find_if() algorithm with a comparison function that takes multiple input arguments, but I'm not sure how to implement it in my code. I have searched for usages of std::find_if() on various sites, but all of them used a comparison function with a single input argument.

using namespace std;

// comparison function
bool range_search(double x, double X1, double X2)
{
    return (x >= X1 && x <= X2) ? true : false;
}

// main   
vector<double> x;

for(int i = 0; i < size; i++){
    x.push_back(...);
};

vector<double>::iterator it = find_if(x.begin(), x.end(), range_search);
int pos_1 = distance(x.begin(), it);
like image 891
Ken Avatar asked Nov 26 '25 00:11

Ken


1 Answers

There is no version of std::find_if() that accepts a predicate with multiple input arguments. std::find_if() iterates through the specified iterator range, passing each element one at a time to the predicate. As such, the predicate must take only 1 input argument, no more, no less. That is why all of the examples you have seen use 1 argument.

The range_search() function you have shown is simply not compatible to use as the predicate itself.

In C++11 and later, you can use a lambda to capture the extra values you want to pass to range_search(), eg:

double X1 = ...;
double X2 = ...;
auto it = find_if(x.begin(), x.end(),
    [X1, X2](double x){ return range_search(x, X1, X2); }
);

Prior to C++11, you can use a functor object instead:

struct range_search_s
{
    double X1, X2;
    range_search_s(double x1, double x2) : X1(x1), X2(x2) {}
    bool operator()(double x) { return range_search(x, X1, X2); }
};

double X1 = ...;
double X2 = ...;
vector<double>::iterator it = find_if(x.begin(), x.end(), range_search_s(X1, X2));
like image 50
Remy Lebeau Avatar answered Nov 28 '25 17:11

Remy Lebeau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!