Advertisement
Guest User

stos

a guest
Apr 2nd, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4. class stos
  5. {
  6. private:
  7. int pojemnosc;
  8. int ile;
  9. std::string* tablica;
  10. public:
  11. stos()
  12. {
  13. this->pojemnosc = 1;
  14. tablica = new std::string[this->pojemnosc];
  15. ile = 0;
  16. }
  17. stos(int pojemnosc)
  18. {
  19. if(pojemnosc < 1 || pojemnosc > 100)
  20. throw std::invalid_argument("pojemnosc musi byc dododatnia i nie wieksza od 100");
  21.  
  22. this->pojemnosc = pojemnosc;
  23. tablica = new std::string[this->pojemnosc];
  24. ile = 0;
  25. }
  26. stos(const std::initializer_list<std::string>& napisy)
  27. {
  28. if(napisy.size() == 0)
  29. throw std::invalid_argument("lista inicjalizacyjna musi byc niepusta");
  30.  
  31. std::initializer_list<std::string>::iterator it;
  32.  
  33. for(it = napisy.begin(); it != napisy.end(); ++it)
  34. {
  35. wloz(*it);
  36. }
  37. }
  38. void wloz(std::string input)
  39. {
  40. if(ile == pojemnosc)//grow array
  41. {
  42. pojemnosc *= 2;
  43. std::string* newArray = new std::string[pojemnosc];
  44. std::copy(tablica,tablica + ile, newArray);
  45. delete[] tablica;
  46. tablica = newArray;
  47. }
  48. ++ile;
  49. tablica[ile-1] = input;
  50. }
  51. std::string sciagnij()
  52. {
  53. //mozna wzic pod uwage przypadek gdy mamy array duzy po uzyciu stos(capacity)
  54. if(ile <= pojemnosc/2)//shrink array
  55. {
  56. pojemnosc /= 2;
  57. std::string* newArray = new std::string[pojemnosc];
  58. std::copy(tablica,tablica + ile, newArray);
  59. delete[] tablica;
  60. tablica = newArray;
  61. }
  62. --ile;
  63. return tablica[ile];
  64. }
  65. std::string sprawdz()
  66. {
  67. if(ile == 0)
  68. throw std::invalid_argument("stos jest pusty");
  69.  
  70. return tablica[ile-1];
  71. }
  72. int rozmiar()
  73. {
  74. return ile;
  75. }
  76. int getCapacity()
  77. {
  78. return this->pojemnosc;
  79. }
  80. };
  81.  
  82. int main()
  83. {
  84. try
  85. {
  86. stos nowyStos = stos(10);
  87. nowyStos.wloz("napis");
  88. std::cout << nowyStos.rozmiar();
  89. std::cout << nowyStos.sciagnij();
  90. std::cout << nowyStos.getCapacity();
  91.  
  92. stos drugiStos = stos({"pierwszy","drugi","trzeci"});
  93.  
  94. //std::cout << nowyStos.sprawdz();
  95. }
  96. catch(const std::exception& e)
  97. {
  98. std::clog << e.what();
  99. }
  100. return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement