fork download
  1. #include <algorithm>
  2. #include <vector>
  3. #include <functional>
  4. #include <iostream>
  5.  
  6. template <typename T> struct Term
  7. {
  8. Term() : coeff(), exponent(0) { }
  9. Term(T c, int e) : coeff(c), exponent(e) { }
  10. T coeff;
  11. int exponent;
  12. };
  13.  
  14. template <typename T> struct Poly
  15. {
  16. typedef Term<T> term_t;
  17. typedef std::vector<term_t> terms_t;
  18. terms_t _terms;
  19.  
  20. Poly(terms_t terms) : _terms(terms) { }
  21.  
  22. void combineLikeTerms()
  23. {
  24. if (_terms.empty())
  25. return;
  26.  
  27. std::sort(_terms.begin(), _terms.end(), order);
  28.  
  29. term_t accum(T(), 0);
  30. std::vector<term_t> result;
  31.  
  32. for (typename terms_t::const_iterator curr = _terms.begin(); curr!= _terms.end(); ++curr)
  33. {
  34. if (curr->exponent == accum.exponent)
  35. accum.coeff += curr->coeff;
  36. else
  37. {
  38. if (accum.coeff != 0)
  39. result.push_back(accum);
  40. accum = *curr;
  41. }
  42. }
  43. if (accum.coeff != 0)
  44. result.push_back(accum);
  45.  
  46. std::swap(_terms, result); // only update if no exception
  47. }
  48.  
  49. private:
  50. static bool order(term_t const& a, term_t const& b)
  51. { return a.exponent > b.exponent; }
  52. };
  53.  
  54. int main()
  55. {
  56. Poly<int>::terms_t terms;
  57. terms.push_back(Term<int>( 4, 1 ));
  58. terms.push_back(Term<int>( 6, 7 ));
  59. terms.push_back(Term<int>(-3, 1 ));
  60. terms.push_back(Term<int>( 5, 5 ));
  61.  
  62. Poly<int> demo(terms);
  63.  
  64. typedef std::vector<Term<int> >::const_iterator It;
  65.  
  66. demo.combineLikeTerms();
  67.  
  68. for (It it = demo._terms.begin(); it!= demo._terms.end(); ++it)
  69. std::cout << (it->coeff>0? " +" : " ") << it->coeff << "x^" << it->exponent;
  70.  
  71. std::cout << "\n";
  72. }
Success #stdin #stdout 0.01s 2816KB
stdin
Standard input is empty
stdout
 +6x^7 +5x^5 +1x^1