Junior — Middle
Can you explain what a binary predicate is in programming?
sobes.tech AI
Answer from AI
A binary predicate is a function or functional object that takes two arguments and returns a boolean value (true or false). It is commonly used for comparing two elements.
In C++, a binary predicate is often used in standard library algorithms (STL), for example, for sorting or searching to determine the order of elements.
An example of a binary predicate is a function that compares two numbers:
#include <iostream>
#include <algorithm>
#include <vector>
// Binary predicate: returns true if a is less than b
bool less_than(int a, int b) {
return a < b;
}
int main() {
std::vector<int> v = {3, 1, 4, 1, 5};
std::sort(v.begin(), v.end(), less_than);
for (int n : v) {
std::cout << n << ' ';
}
return 0;
}
Here, less_than is a binary predicate that defines the sorting order.
Thus, a binary predicate is a function with two input parameters that returns a bool, used for comparing or checking conditions between two elements.