简体   繁体   English

如何使用带有堆栈的结构?

[英]How to use struct with stack?

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?但我的问题是当我们使用 struct 而不是 int/char 类型变量时如何推送和访问数据? 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 .您可以通过使用Aggregate Initialization或向您的结构或std::stack::emplace添加构造函数来推送到std::stack

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() .要访问该元素,只需调用std::stack::top()

st top = s.top();

or by using C++17 Structured binding declaration :或使用 C++17 结构化绑定声明

auto [index, value] = s.top();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM