[英]How to add an element into the vector of pointers?
我有這個:
std::vector <BinaryTree*> children;
BinaryTree
是一個類。 如何在此向量中添加元素?
我試過了children.push_back(X)
,其中X
是類的一個實例,但它給了我這個錯誤:
不能將參數1從'BinaryTree'轉換為'BinaryTree * &&'
只需使用push_back()
並將指針傳遞給BinaryTree
的實例:
std::vector <BinaryTree*> children;
BinaryTree* pTree = new BinaryTree();
children.push_back(pTree);
...
delete pTree;
為了避免手動內存管理,如果需要引用語義,請使用智能指針而不是原始指針:
#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
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
最后,如果您根本不需要引用語義並希望將二進制樹視為值,您甚至可以考慮定義std::vector<BinaryTree>
:
std::vector<BinaryTree> children;
BinaryTree tree;
children.push_back(tree);
從模板參數中省略星號*
:
std::vector<BinaryTree> children;
您希望子項保存數據,而無需像new BinaryTree
那樣手動/動態分配內存。
這實際上取決於誰應該擁有指針。 在最簡單的情況下,向量不擁有它們,然后傳遞BinaryTree
對象的地址。
BinaryTree b = ...;
children.push_back(&b);
但你必須確保b
至少和children
一樣長壽。
如果向量擁有指針,那么您應該存儲智能指針以避免必須處理內存管理:
std::vector<std::unique_ptr<BinaryTree>> children;
children.push_back(std::unique_ptr<BinaryTree>(new BinaryTree(args)));
如果您不知道所有這些“所有權”業務的含義,那么您最好使用簡單的對象向量:
std::vector<BinaryTree> children;
std::vector<SomeObject*> objectVector;
objectVector.push_back(new SomeObject());
我是怎么做的
你有指針的矢量:
std::vector <BinaryTree*> children;
所以添加元素的正確方法是:
BinaryTree* child = new BinaryTree();
children.push_back(child);
做這樣的事情時要小心:
{
BinaryTree child;
children.push_back(&child);
}
因為這樣一個元素的生命周期可能比向量的生命周期短,你可能最終試圖訪問一個不再存在的元素(懸空指針),這會產生未定義的行為 。 完成后也不要忘記delete
這些元素。
但是首先考慮使用對象向量(即std::vector<BinaryTree>
)總是好的,因為這會為你處理那種丑陋的內存管理。
children.push_back(&X);
這將有效,但請記住,一旦你的對象離開作用域,它的刪除器將被調用,你將留下一個無效的指針。
children.push_back(&X);
傳遞地址,就像使用它作為指針一樣。 但問題是,如果該實例超出范圍,那么最好這樣做
BinaryTree* X = new BinaryTree;
children.push_back(X);
這將確保X永遠不會超出范圍,但是當您完成它時必須手動刪除它。
該vector
包含指向 BinaryTree
類型的對象的指針 。 你需要
BinaryTree bt;
children.push_back( &bt );
但是你必須確保bt
對象的生命周期至少與vector
的生命周期相匹配。
你可能想要這個
children.push_back( new BinaryTree );
但在這種情況下,您必須在vector
包含的指針上調用delete
以防止內存泄漏。
很明顯,這兩種選擇都不容易管理。 一個簡單的改變是讓容器按值存儲元素。
std::vector<BinaryTree> children;
BinaryTree bt;
children.push_back( bt );
如果必須存儲指針,請使用智能指針來保存它們。
std::vector<std::unique_ptr<BinaryTree>> children;
children.push_back( new BinaryTree );
現在,您無需擔心在清空向量之前刪除對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.