Advertisement
yepp

expr

Mar 11th, 2017 (edited)
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <vector>
  2. #include <iostream>
  3. #include <functional>
  4.  
  5. class Function {
  6. public:
  7.     virtual float eval(float x) {return 0;};
  8. };
  9.  
  10. class Expr {
  11. public:
  12.     std::vector<Function*> functions;
  13.     Expr() {}
  14.     Expr(Function* f) {
  15.         functions.push_back(f);
  16.     }
  17.  
  18.     void addFunc(Function* f) {
  19.         functions.push_back(f);
  20.     }
  21.  
  22.     float eval(float x) {
  23.         float ret = 1.0;
  24.         for (int i = 0; i < functions.size(); i++) {
  25.             ret *= functions[i]->eval(x);
  26.         }
  27.         return ret;
  28.     }
  29.  
  30. };
  31.  
  32. Expr* prod(Expr* f, Expr* g) {
  33.     Expr* h = new Expr();
  34.     for (int i = 0; i < f->functions.size(); i++)
  35.         h->addFunc(f->functions[i]);
  36.     for (int i = 0; i < g->functions.size(); i++)
  37.         h->functions.push_back(g->functions[i]);
  38.     return h;
  39. }
  40.  
  41. class Polynomial : public Function {
  42. private:
  43.     std::vector<float> coefs;
  44. public:
  45.     float eval(float x) {
  46.         float ret = 0.0;
  47.         for (int i = 0; i < coefs.size(); i++) {
  48.             ret += coefs[i] * pow(x, i);
  49.  
  50.         }
  51.         return ret;
  52.     }
  53.  
  54.     Polynomial(std::vector<float> &v) {
  55.         for (int i = 0; i < v.size(); i++) {
  56.             coefs.push_back(v[i]);
  57.         }
  58.     }
  59. };
  60.  
  61. class Sin : public Function {
  62. public:
  63.     float eval(float x) {
  64.         return sin(x);
  65.     }
  66. };
  67.  
  68. int main() {
  69.     Function* kovi = new Sin();
  70.     std::vector<float> coeffs = {1,2,3,4,5};
  71.     Function* mester = new Polynomial(coeffs);
  72.  
  73.     Expr* koviExpr = new Expr(kovi);
  74.     Expr* mesterExpr = new Expr(mester);
  75.  
  76.     std::cout << "Kovi: " << koviExpr->eval(4.0) << std::endl;
  77.     std::cout << "mester: " << mesterExpr->eval(4.0) << std::endl;
  78.     std::cout << "Kovimester: " << prod(koviExpr, mesterExpr)->eval(4.0) << std::endl;
  79.  
  80.     int a; std::cin >> a;
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement