如何在指针向量中添加元素?

use*_*010 4 c++ pointers vector

我有这个:

std::vector <BinaryTree*> children;

哪个BinaryTree是班级.如何在此向量中添加元素?

我想children.push_back(X)这里X是一个类的实例,但它给了我这个错误:

不能将参数1从'BinaryTree'转换为'BinaryTree*&&'

And*_*owl 10

只需使用push_back()并将指针传递给以下实例BinaryTree:

std::vector <BinaryTree*> children;
BinaryTree* pTree = new BinaryTree();
children.push_back(pTree);
...
delete pTree;
Run Code Online (Sandbox Code Playgroud)

为了避免手动内存管理,如果需要引用语义,请使用智能指针而不是原始指针:

#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
Run Code Online (Sandbox Code Playgroud)

std::shared_ptr<>类模板是C++ 11标准库的一部分.在C++ 03中,您可以使用(几乎)等效的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
Run Code Online (Sandbox Code Playgroud)

最后,如果您根本不需要引用语义并希望将二进制树视为值,您甚至可以考虑定义std::vector<BinaryTree>:

std::vector<BinaryTree> children;
BinaryTree tree;
children.push_back(tree);
Run Code Online (Sandbox Code Playgroud)