代码我应该在stack声明中使用& g吗?:
#include<iostream>
#include<stack>
using namespace std;
struct node{
int data;
struct node *link;
};
main(){
stack<node> s;
struct node *g;
g = new node;
s.push(g);
}
stack push()要么复制对象,要么将其移动。如果您不需要共享对节点对象的访问权限,请将它们(而不是指针)通过移动语义堆叠:
std::stack<node> st;
st.push(node());
http://en.cppreference.com/w/cpp/container/stack/push
我认为您在s.push(g)
上有错误,因为g
的类型为node*
,因此您不能将其放入stack<node>
中。我认为您应该声明stack < node*>
,因为它易于与new
操作一起使用。