I have this:
std::vector <BinaryTree*> children;
where BinaryTree
is a class. How can I add an element into this vector?
I tried children.push_back(X)
where X
is an instance of the class but it gives me this error:
cannot convert parameter 1 from 'BinaryTree' to 'BinaryTree *&&'
Just use the push_back()
and pass a pointer to an instance of BinaryTree
:
std::vector <BinaryTree*> children;
BinaryTree* pTree = new BinaryTree();
children.push_back(pTree);
...
delete pTree;
In order to avoid manual memory management, if you need reference semantics, use smart pointers instead of raw pointers:
#include <memory> // For std::shared_ptr
std::vector <std::shared_ptr<BinaryTree>> children;
std::shared_ptr<BinaryTree> pTree = std::make_shared<BinaryTree>();
children.push_back(pTree);
...
// No need to delete pTree
The std::shared_ptr<>
class template is part of the C++11 Standard Library. In C++03, you could use the (almost) equivalent boost::shared_ptr<>
:
#include <boost/shared_ptr.hpp> // For std::shared_ptr
std::vector <boost::shared_ptr<BinaryTree>> children;
boost::shared_ptr<BinaryTree> pTree = boost::make_shared<BinaryTree>();
children.push_back(pTree);
...
// No need to delete pTree
Finally, if you do not need reference semantics at all and want to treat your binary trees as values instead, you can even consider defining a std::vector<BinaryTree>
:
std::vector<BinaryTree> children;
BinaryTree tree;
children.push_back(tree);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With