Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a setOfStacks in c++

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?

like image 718
user3916798 Avatar asked Jun 07 '26 00:06

user3916798


1 Answers

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.

like image 175
The Dark Avatar answered Jun 10 '26 08:06

The Dark