Hoi,
Ik ben uitgedaagd om mijn eigen stack class te schrijven om te oefenen met pointers.
Later "moet" ik dit herschrijven en smart pointers gebruiken.
Voor zover heb ik dit :
main.cpp
#include <iostream>
#include <string>
#include "stack.h"
int main() {
Stack s;
std::string line;
while (true) {
std::cout << "> ";
std::getline(std::cin, line);
if (line == "exit") break;
else if (line == "pop") std::cout << "Popped " << s.pop() << "\n";
else if (line == "top") std::cout << "Top value: " << s.top() << "\n";
else if (line.compare(0, 4, "push") == 0) {
int val = std::stoi(line.substr(5));
s.push(val);
} else if (line == "print") {
Stack copy = s;
while (copy.size() > 0) {
std::cout << copy.pop() << " ";
}
std::cout << "\n";
} else {
std::cout << "Commands: push <n>, pop, top, exit\n";
}
}
}
stack.h
#pragma once
class Stack {
public:
// Creates an empty stack with capacity 4
Stack();
// Creates a copy of your stack
Stack(const Stack& o);
// Assignment operator
Stack& operator=(const Stack& o);
// Destructor
~Stack();
// We'll ignore move constructor and move assignment.
// Adds a new value to the stack
void push(int value);
// Checks the value at the top of the stack
int top();
// Removes the value at the top of the stack (returning it)
int pop();
// Returns the number of elements in the stack
int size();
private:
int* buffer;
int capacity;
int number_of_items;
};
stack.cpp
#include "stack.h"
#include <memory>
Stack::Stack() {
capacity = 4;
buffer = new int[capacity];
number_of_items = 0;
}
Stack::Stack(const Stack& o){
capacity = o.capacity;
number_of_items = o.number_of_items;
buffer = new int[capacity];
for (int i {}; i < number_of_items; i++) {
buffer[i] = o.buffer[i];
}
}
Stack& Stack::operator =(const Stack& o) {
capacity = o.capacity;
number_of_items = o.number_of_items;
delete[] buffer;
buffer = new int[capacity];
for (int i {}; i < number_of_items; i++) {
buffer[i] = o.buffer[i];
}
return *this;
}
Stack::~Stack(){
delete[] buffer;
}
void Stack::push(int value){
if (number_of_items <= capacity) {
++number_of_items;
buffer[number_of_items] = value;
} else {
capacity = capacity * 2 ;
int* new_buffer = new int[capacity];
for (int i {}; i < number_of_items; i++) {
new_buffer[i] = buffer[i];
};
delete[] buffer;
buffer = new int[capacity];
buffer = new_buffer;
}
}
int Stack::top() {
return buffer[number_of_items -1];
}
int Stack::pop() {
return buffer[number_of_items - 1];
--number_of_items;
}
int Stack::size() {
return number_of_items;
}
maar als ik doe "push 4 " en daarna print dan wordt er een doorlopende loop gestart waar alleen maar nullen wordt geprint.
Nu vraag ik me af of iemand me kan helpen om uit te vinden waar ik verkeerd gedacht heb of waar de code verkeerd is