fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <iterator>
  7. using namespace std;
  8.  
  9. template<class T>
  10. T fromString(string s) {
  11. T result;
  12. stringstream ss(s);
  13. ss >> result;
  14. return result;
  15. }
  16.  
  17. std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
  18. std::stringstream ss(s);
  19. std::string item;
  20. while (std::getline(ss, item, delim)) {
  21. elems.push_back(item);
  22. }
  23. return elems;
  24. }
  25.  
  26.  
  27. std::vector<std::string> split(const std::string &s, char delim) {
  28. std::vector<std::string> elems;
  29. split(s, delim, elems);
  30. return elems;
  31.  
  32. }
  33.  
  34. void displ(vector<string> el) {
  35. cout << "\n\n";
  36. copy(el.begin(), el.end(), ostream_iterator<string>(cout, "\t"));
  37. cout << "\n\n";
  38. }
  39.  
  40. class Foo {
  41. double wyn;
  42. size_t wielkoscTablicy;
  43. double *tab;
  44. double x;
  45.  
  46. public:
  47. Foo(double wn, double x, size_t w):
  48. wyn(wn),
  49. x(x),
  50. wielkoscTablicy(w)
  51. {
  52. tab = new double[w];
  53.  
  54. for(size_t i = 0; i < w; ++i) {
  55. tab[i] = i*2;
  56. }
  57. }
  58.  
  59. string serialize() {
  60. string tab = to_string(wielkoscTablicy) + ":";
  61. for(size_t i = 0; i < wielkoscTablicy; ++i) {
  62. tab += to_string(this->tab[i]) + ",";
  63. }
  64.  
  65. stringstream out;
  66. out << wyn << "-" << x << "-" << tab << "\n";
  67. return out.str();
  68. }
  69.  
  70. void deserialize(string s) {
  71. vector<string> all = split(s, '-');
  72. displ(all);
  73. this->wyn = fromString<double>(all[0]);
  74. this->x = fromString<double>(all[1]);
  75.  
  76. vector<string> alltab = split(all[2], ':');
  77. this->wielkoscTablicy = fromString<size_t>(alltab[0]);
  78. displ(alltab);
  79. vector<string> tab = split(alltab[1], ',');
  80. displ(tab);
  81. if(this->tab) delete[] this->tab;
  82. this->tab = new double[this->wielkoscTablicy];
  83. for(size_t i = 0; i < this->wielkoscTablicy; ++i) {
  84.  
  85. this->tab[i] = fromString<double>(tab[i]);
  86. }
  87. }
  88. };
  89.  
  90. int main() {
  91. Foo f(10, 12.5, 5);
  92. string fs = f.serialize();
  93. f.deserialize(fs);
  94. cout << fs << endl;
  95. return 0;
  96. }
Success #stdin #stdout 0s 2996KB
stdin
Standard input is empty
stdout

10	12.5	5:0.000000,2.000000,4.000000,6.000000,8.000000,
	



5	0.000000,2.000000,4.000000,6.000000,8.000000,
	



0.000000	2.000000	4.000000	6.000000	8.000000	
	

10-12.5-5:0.000000,2.000000,4.000000,6.000000,8.000000,