I'm a complete newbie at C . I want to create my own predicate. But the part with bool operator seems to be wrong (at least in my humble opinion). Could someone give me a hint? I don't want to change the overall structure of this idea, I'm just sure I don't understand some details about operator () implementation or something related to classes in c .
#include <iostream>
#include <vector>
class Predicate
{
private:
int number = 0;
public:
Predicate() = default;
Predicate(const int number)
{
this->number = number;
}
bool operator()(int value) const
{
Predicate *pred = new Predicate();
bool result = pred->operator()(value);
return result;
}
};
class Even : public Predicate
{
bool operator()(int value) const
{
return value % 2 == 0;
}
};
class Negative : public Predicate
{
bool operator()(int value) const
{
return value < 0;
}
};
int count(const std::vector<int> &elements, const Predicate &predicate)
{
int count = 0;
for (int index = 0; index < elements.size(); index)
{
if (predicate(elements[index]))
{
count;
}
}
return count;
}
int main()
{
const std::vector<int> elements{-7, 12, -11, 2, 9, -4, -6, 5, 23, -1};
std::cout << count(elements, Even()) << " " << count(elements, Negative()) << std::endl;
}
CodePudding user response:
What you need is:
- define
Predicate
as an abstract type, - implements different versions of it.
Predicate
as an abstract type:
class Predicate {
public:
virtual bool operator(int v) const = 0;
};
Implementing (realising) a given Predicate
:
class IsNegative : public Predicate { // means IsNegatives are Predicates
public:
virtual bool operator(int v) const { return v<0; } // realisation of the operator
};