Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <iostream>
- #include <functional>
- class Function {
- public:
- virtual float eval(float x) {return 0;};
- };
- class Expr {
- public:
- std::vector<Function*> functions;
- Expr() {}
- Expr(Function* f) {
- functions.push_back(f);
- }
- void addFunc(Function* f) {
- functions.push_back(f);
- }
- float eval(float x) {
- float ret = 1.0;
- for (int i = 0; i < functions.size(); i++) {
- ret *= functions[i]->eval(x);
- }
- return ret;
- }
- };
- Expr* prod(Expr* f, Expr* g) {
- Expr* h = new Expr();
- for (int i = 0; i < f->functions.size(); i++)
- h->addFunc(f->functions[i]);
- for (int i = 0; i < g->functions.size(); i++)
- h->functions.push_back(g->functions[i]);
- return h;
- }
- class Polynomial : public Function {
- private:
- std::vector<float> coefs;
- public:
- float eval(float x) {
- float ret = 0.0;
- for (int i = 0; i < coefs.size(); i++) {
- ret += coefs[i] * pow(x, i);
- }
- return ret;
- }
- Polynomial(std::vector<float> &v) {
- for (int i = 0; i < v.size(); i++) {
- coefs.push_back(v[i]);
- }
- }
- };
- class Sin : public Function {
- public:
- float eval(float x) {
- return sin(x);
- }
- };
- int main() {
- Function* kovi = new Sin();
- std::vector<float> coeffs = {1,2,3,4,5};
- Function* mester = new Polynomial(coeffs);
- Expr* koviExpr = new Expr(kovi);
- Expr* mesterExpr = new Expr(mester);
- std::cout << "Kovi: " << koviExpr->eval(4.0) << std::endl;
- std::cout << "mester: " << mesterExpr->eval(4.0) << std::endl;
- std::cout << "Kovimester: " << prod(koviExpr, mesterExpr)->eval(4.0) << std::endl;
- int a; std::cin >> a;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement