Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Stack {
- public:
- Stack(size_t buffer = 100)
- : buffer_(buffer), stack_(new int [buffer_]), index_(0) {
- }
- Stack(const initializer_list<int> ilst)
- : buffer_(ilst.size()), stack_(new int[buffer_]), index_(0) {
- for (auto value : ilst) push(value);
- }
- Stack(const Stack& stack)
- : buffer_(stack.capacity()), stack_(new int[buffer_]), index_(stack.index_) {
- for (auto i = 0U; i < index_; ++i) stack_[i] = stack.stack_[i];
- }
- Stack(Stack&& stack)
- : buffer_(stack.capacity()), stack_(move(stack.stack_)), index_(0) {
- }
- ~Stack() {
- if (stack_ != nullptr) {
- delete[] stack_;
- stack_ = nullptr;
- buffer_ = index_ = 0;
- }
- }
- Stack operator=(const Stack& stack) {
- if (this != &stack) {
- buffer_ = stack.buffer_;
- index_ = stack.index_;
- for (auto i = 0U; i < index_; ++i) stack_[i] = stack.stack_[i];
- }
- return *this;
- }
- Stack operator=(Stack&& stack) {
- if (this != &stack) {
- buffer_ = stack.buffer_;
- index_ = stack.index_;
- stack_ = move(stack.stack_);
- }
- return *this;
- }
- void push(int value) {
- if (index_ == buffer_) {
- auto tmp = *this;
- delete [] stack_;
- buffer_ *= 2;
- stack_ = new int[buffer_];
- for (auto i = 0U; i < index_; ++i) stack_[i] = tmp.stack_[i];
- }
- stack_[index_] = value;
- ++index_;
- }
- void push(const initializer_list<int> ilst) {
- for (auto value : ilst) push(value);
- }
- int& top() {
- return stack_[index_ - 1];
- }
- void pop() {
- --index_;
- }
- bool empty()const {
- return 0 == index_;
- }
- size_t size()const {
- return index_;
- }
- size_t capacity()const {
- return buffer_;
- }
- private:
- size_t buffer_;
- int* stack_;
- size_t index_;
- };
- void show(Stack& a) {
- cout << "top: ";
- if (!a.empty()) cout << a.top() << '\n';
- else puts("empty");
- cout
- << "size: " << a.size() << '\n'
- << "capacity: " << a.capacity() << '\n'
- << "--------------\n";
- }
- int main() {
- Stack a;
- for (auto i = 1; i <= 150; ++i) a.push(i);
- show(a);
- for (auto i = 0; i < 25; ++i) if (!a.empty()) a.pop();
- show(a);
- Stack b = a;
- show(b);
- b.top() = 777;
- show(b);
- a = b;
- show(a);
- Stack c({ 1, 3, 5, 7, 9 });
- show(c);
- c.push({ 2, 4, 6, 8 });
- show(c);
- Stack d(c);
- show(d);
- Stack e(Stack({ 10, 11, 12, 13, 14, 15 }));
- show(e);
- while (!a.empty()) a.pop();
- show(a);
- cout.put('\n');
- system("pause");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement