Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an element into the vector of pointers?

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 *&&'

like image 298
user2116010 Avatar asked Dec 01 '22 20:12

user2116010


1 Answers

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);
like image 97
Andy Prowl Avatar answered Dec 16 '22 08:12

Andy Prowl