我写了一个Stack
两边都用的类,即两个堆栈合二为一。一个从[0]
直到[someplace - 1]
,一个从[capacity-1]
直到[someplace +1]
。
一切都很好,但是当我的数组已满时,我在将内存加倍时遇到了一些问题。我的代码一开始可以加倍,但是当它需要再加倍时,它会给我一些奇怪的错误。
_ctrlvalidHeappointer
临界区错误
这是我的代码。代码中也有一些解释。当我在堆栈中推送太多元素时,它会失败。
string firstname = "asasasasasaasasasasassasasasaasas";
string secondname= "asasdasfregeasasasasasgergergererg";
for (int i = 0; i < firstname.length(); i++)
{
a.push_at_first(firstname.at(i));
}
for (int i = 0; i < secondname.length(); i++)
{
a.push_from_end(secondname.at(i));
}
这是我的课
using namespace std;
template <class T>
class Stack{
public:
Stack();
~Stack();
Stack(const Stack<T>& ob);
void double_size();
void push_at_first(T mydata);
void push_from_end(T mydata);
T & operator = (Stack<T> ob);
private:
int top;
int top2;
T * stack;
int capacity;
};
template <class T>
T& Stack<T>::operator = (Stack<T> ob)
{
if(capacity == ob.capacity){
top = ob.top;
top2 = ob.top2;
for (int i = 0; i < capacity; i++)
{
stack[i] = ob.stack[i];
}
return *this;}
else
{
capacity = ob.capacity;
stack = new T[capacity];
for (int i = 0; i < capacity; i++)
{
stack[i] = ob.stack[i];
}
}
}
template <class T>
Stack<T>::Stack (const Stack<T>& ob) :capacity(ob.capacity)
{
stack = new T[capacity];
top = ob.top;
top2=ob.top2;
for (int i = 0; i < capacity; i++)
{
stack[i] = ob.stack[i];
}
}
template <class T>
Stack<T>::~Stack()
{
delete [] stack;
}
template <class T>
Stack<T>::Stack()
{
capacity = 17;
top = 0;
top2 = capacity-1;
stack = new T[capacity];
}
template <class T>
void Stack<T>::push_at_first(T mydata)
{
if ( (top + 1) == (top2 -1) ) // 1 : because I want to Be a Empty Space between Two Stack so i can tell the difference
double_size();
stack[++top] = mydata;
}
template <class T>
void Stack<T>::push_from_end(T mydata)
{
if( (top + 1) == (top2 -1) ) // 1 : because I want to Be a Empty Space between Two Stack so i can tell the difference
double_size();
stack[--top2] = mydata;
}
template <class T>
void Stack<T>::double_size()
{
Stack<T> temp(*this);
capacity *= 2;
stack = new T[capacity];
top = temp.top;
top2 = capacity - (temp.capacity - temp.top2);// capacity - number of data in stack of temp ;
// if we have something in first stack then copy 0 to top elements of temp.stack to stack
if(top > 0)
{
for (int i = 0; i <= top ; i++)
{
stack[i] = temp.stack[i];
}
}
// There is Something Wrong Down here ! i can't figure out what !
if(top2 < capacity - 1)
{
for (int i = capacity-1; i >= top2; i--)
{
stack[i] = temp.stack[i-(temp.capacity)];
}
}
}