如何将结构与堆栈一起使用?

How to use struct with stack?

通常当我们使用堆栈时,我们会这样做....

stack<int>st;
st.push(1);
st.push(2);
st.push(3);

cout<<st.top<<"\n"  

但我的问题是当我们使用struct而不是int/char类型变量时如何推送和访问数据?例如...

struct st
{
  int index, value;
};
int main()
{
  stack<st>STACK;
  /*
     code
  */

}

现在,我如何将元素压入堆栈并访问它们?

您可以使用 Aggregate initialization 或向您的结构或 std::stack::emplace 添加构造函数来推送到 std::stack

通过使用构造函数:

struct st
{
  st(int _index, int _value) : index(_index), value(_value) {}
  int index, value;
};

std::stack<st> s;
s.push(st(10, 20));

通过使用聚合初始化:

std::stack<int> s;
s.push({10, 20});

要访问元素,只需调用 std::stack::top()

st top = s.top();

或使用 C++17 Structured binding declaration:

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