Normally when we use stack we do this....
stack<int>st;
st.push(1);
st.push(2);
st.push(3);
cout<<st.top<<"\n"
But my question is how to push and access data when we use struct instead of int/char type variable? For example...
struct st
{
int index, value;
};
int main()
{
stack<st>STACK;
/*
code
*/
}
Now, here how can I push element in stack and access them?
You can push to std::stack
by using Aggregate initialization , or adding a constructor to your structure or std::stack::emplace
.
By using constructor:
struct st
{
st(int _index, int _value) : index(_index), value(_value) {}
int index, value;
};
std::stack<st> s;
s.push(st(10, 20));
By using Aggregate initialization:
std::stack<int> s;
s.push({10, 20});
To access the element simply call std::stack::top()
.
st top = s.top();
or by using C++17 Structured binding declaration :
auto [index, value] = s.top();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.