I am making a program that checks if stacks are equаl.
With this code, I am getting an error:
HEAP[ldf.exe]: Invalid address specified to RtlValidateHeap
It works until returning answer in func equal_stacks
, so maybe a problem has to do something with deleting stacks that he gets when function starts?
Destructor was written by my teacher, so it is probably right. Maybe a problem is somewhere in equals_stacks
function?
#include <iostream>
template<typename T>
class stackm{
int capacity;
int count;
T* data;
public:
stackm();
~stackm();
void push(const T& elem);
void push(T&& elem);
void pop();
T& top();
const T& top() const;
int size() const;
};
template<typename T>
stackm<T>::stackm() {
capacity = 1;
count = 0;
data = new T[1];
}
template<typename T>
stackm<T>:: ~stackm() {
delete[] data;
}
template<typename T>
void stackm<T>::pop() {
--count;
}
template <typename T>
void stackm<T>::push(const T& elem) {
if (this->count == this->capacity) {
size_t new_capacity = capacity * 2;
T* new_data = new T[new_capacity];
for (size_t i = 0; i < this->capacity; ++i) {
new_data[i] = std::move(this->data[i]);
}
delete[] this->data;
this->capacity = new_capacity;
this->data = new_data;
}
data[count++] = elem;
}
template <typename T>
void stackm<T>::push(T&& elem) {
if (this->count == this->capacity) {
size_t new_capacity = capacity * 2;
T* new_data = new T[new_capacity];
for (size_t i = 0; i < this->capacity; ++i) {
new_data[i] = std::move(this->data[i]);
}
delete[] this->data;
this->capacity = new_capacity;
this->data = new_data;
}
data[count++] = elem;
}
template <typename T>
int stackm<T>::size() const {
return count;
}
template <typename T>
T& stackm<T>::top() {
return data[count - 1];
}
template <typename T>
const T& stackm<T>::top() const {
return data[count - 1];
}
template<typename Stack>
bool equal_stacks(Stack s1, Stack s2) {
if (s1.size() != s2.size()) {
return false;
}
while (s1.size() != 0) {
if (s2.top() != s1.top()) {
return false;
}
s1.pop();
s2.pop();
}
return true;
}
int main() {
stackm<int> stac1 = stackm<int>();
stackm<int> sd23 = stackm<int>();
sd23.push(23);
sd23.push(45);
std::cout << equal_stacks<stackm<int>>(stac1, sd23);
}