fork(4) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <sstream>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. string to_string(const vector<int>& poly)
  9. {
  10. ostringstream os;
  11. size_t deg = poly.size();
  12.  
  13. if(deg > 2)
  14. {
  15. --deg;
  16. os << poly[deg] << "x^" << deg;
  17. }
  18.  
  19. os.setf(ios_base::showpos);
  20.  
  21. while(deg-- > 2)
  22. {
  23. os << poly[deg] << "x^" << deg;
  24. }
  25.  
  26. os << poly[deg--] << "x";
  27. os << poly[deg];
  28.  
  29. return os.str();
  30. }
  31.  
  32. vector<int> from_string(const string& str)
  33. {
  34. istringstream is(str);
  35. vector<int> result;
  36. char c;
  37. int x = 0;
  38. while(is.get(c))
  39. {
  40. switch(c)
  41. {
  42. case '+':
  43. case '-':
  44. is.putback(c);
  45. is >> x;
  46. result.push_back(x);
  47. break;
  48. case '^':
  49. is >> x;
  50. break;
  51. default:
  52. if(isdigit(c))
  53. {
  54. is.putback(c);
  55. is >> x;
  56. result.push_back(x);
  57. }
  58. break;
  59. }
  60. }
  61. reverse(result.begin(), result.end());
  62. return result;
  63. }
  64.  
  65. int main()
  66. {
  67. vector<int> koef = {5, -5, 3};
  68. string s = to_string(koef);
  69.  
  70. cout << s << endl;
  71.  
  72. vector<int> result = from_string(s);
  73.  
  74. for(int i : result)
  75. {
  76. cout << i << " ";
  77. }
  78. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
3x^2-5x+5
5 -5 3