I'm making a binary expression tree, and to do so I'm reading in values and putting them into a tree node and a pointer to that tree node into a stack. How do I use the STL stack implementation with pointers to my TreeNode class?

relevant code:

stack<TreeNode> s; 

TreeNode * a = new TreeNode(val);
s.push(a);

TreeNode is a class I created.

gives this error:

treecalc.cpp:54: error: no matching function for call to ‘std::stack<TreeNode, std::deque<TreeNode, std::allocator<TreeNode> > >::push(TreeNode*)’
/usr/include/c++/4.2.1/bits/stl_stack.h:178: note: candidates are: void std::stack<_Tp, _Sequence>::push(const typename _Sequence::value_type&) [with _Tp = TreeNode, _Sequence = std::deque<TreeNode, std::allocator<TreeNode> >]

Edited 6 Years Ago by Nick Evan: Posts merged

How do I use the STL stack implementation with pointers to my TreeNode class?

You had a stack of TreeNode objects, not pointers to such. So ..

stack<TreeNode * > s; 

TreeNode * a = new TreeNode(val);
s.push(a);

I'm making a binary expression tree, and to do so I'm reading in values and putting them into a tree node and a pointer to that tree node into a stack. How do I use the STL stack implementation with pointers to my TreeNode class?

relevant code:

stack<TreeNode> s; 

TreeNode * a = new TreeNode(val);
s.push(a);

TreeNode is a class I created.

You have to declare the stack with a template prameter of TreeNode*:

stack<TreeNode*> s;
TreeNode* a = new TreeNode( val );
s.push(a);

That should do the trick. Remember that the template prameter is always atype and an object is a different type than a pointer to that type of object.

This article has been dead for over six months. Start a new discussion instead.