I am trying to implement a set of stacks, using vector in c++. So I first declare a std::vector of the type std::stack and then do the normal push and pop operations on the stack in the vector. The stack has a threshold. if the stack in the vector has reached its threshold then i add a new stack to the vector. The implementation is as shown below-
#define threshold 3
class setOfStacks{
std::vector<std::stack<int> > *stacks;
public:
setOfStacks(){
stacks = new std::vector<std::stack<int> >();
};
~setOfStacks(){};
void push(int d){
if(stacks->size()==0){
std::stack<int> newStack;
newStack.push(d);
stacks->push_back(newStack);
}
else{
std::stack<int> s = stacks->back();
std::cout<<s.size()<<"\n";
if(s.size()!=threshold){
s.push(d);
}
else{
std::stack<int> newStack;
newStack.push(d);
stacks->push_back(newStack);
}
std::cout<<s.size()<<"\n";
}
}
void pop(){
if(stacks->size()==0){
std::cout<<"No elements in the stack\n";
}
else{
std::stack<int> s;
s = stacks->back();
if(!s.empty()){
std::cout<<s.top()<<" is being removed\n";
s.pop();
}
else{
stacks->pop_back();
pop();
}
}
}
};
int main(){
setOfStacks stackSet;
stackSet.push(1);
stackSet.push(2);
stackSet.push(3);
stackSet.push(4);
stackSet.push(5);
stackSet.push(6);
stackSet.push(7);
stackSet.push(8);
stackSet.push(9);
stackSet.pop();
stackSet.pop();
stackSet.pop();
stackSet.pop();
return 0;
}
The problem I am facing- 1 gets inserted into the first stack and the stack is inserted into vector. when I try inserting 2, the stack reference returned from the vector contains 1 in it, its size is below threshold which is 3 and thus 2 is pushed into the stack. But when I try inserting 3 the stack reference returned to be by vector does not have 2 in it, it again only contains 1. I am unable to figure out why this happens? Can someone please help me with this?
This line:
std::stack<int> s = stacks->back();
takes a copy of the stack<int> from stacks. Then when you push into it, you are only pushing into the copy.
Change it to a reference:
std::stack<int> &s = stacks->back();
Then when you make changes using the reference, the change will be reflected in your vector of stacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With