Hi. I want to implement a fill() method for my own implemented Stack class, that instead of just pushing one element when called, it keeps pushing elements on the stack until it is full. What I have done is I just put a for loop inside the old push() method of my stack, but it doesn't work as intended. It still pushes only one time when called. How do I get it to push continuously until the stack is full?
1 2 3 4 5 6 7 8 9 10
template<typename T, int N>
void Stack<T, N>::push(T x) {
if (topLevel >= N - 1) {
cout<<"The stack is full!\n";
return;
}
for(int i=0;i<=N;i++){
stackArray[++topLevel] = x;
}
}
Tried it this way and it generates an endless loop. It seems my condition is always true, but I don't understand why. In main() I declared my stack as Stack<int, 8> bucket1; so N should be 8 when running that while loop, right?
1 2 3 4 5 6
template<typename T, int N>
void Stack<T, N>::fill(T x){
while (topLevel <N) {
stackArray[topLevel++] = x;
}
}
Nevermind, I figured it out. The loop was endless because I forgot my topLevel was initiated at -1 and not 0. I feel so dumb. Thank you keskiverto for helping!