在C++中,你可以通過重載operator()來實現對謂詞運算符的重載
#include<iostream>
#include<vector>
#include<algorithm>
class MyPredicate {
public:
bool operator()(int value) const {
return value % 2 == 0;
}
};
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
MyPredicate predicate;
auto result = std::find_if(numbers.begin(), numbers.end(), predicate);
if (result != numbers.end()) {
std::cout << "First even number found: " << *result<< std::endl;
} else {
std::cout << "No even numbers found."<< std::endl;
}
return 0;
}
在這個示例中,我們創建了一個名為MyPredicate的類,它重載了operator()。這個操作符接受一個整數值并返回一個布爾值,表示該值是否為偶數。然后我們使用std::find_if算法和MyPredicate對象來查找向量中的第一個偶數。