簡體   English   中英

如何將字符串推送到 shared_ptr 的向量中?

[英]How to push a string into a vector of shared_ptr?

如果我有一個共享指針向量(V1)和一個包含很多字符串的向量(V2)。 如何使用 V1 內部的 shared_ptr 指向 V2 內部的元素?

前任:

std::vector< std::shared_ptr< SImplementation > > V1;  
std::vector < std::string > V2; // there are strings in the V2 already

for(auto i : V2){
    V1.push_back(i) // I tried this way, but it does not work because of the different types, different types mean int, string, unsigned long
}

我可以使用迭代器或使用另一個 shared_pointer 指向 V2 中的字符串嗎?

std::shared_ptr是管理 memory 所有權的工具。 這里的問題是std::vector已經管理了它的 memory。 此外,當調整或擦除元素時, std::vector會使指向其元素的引用和指針無效。

您可能想要的是擁有兩個共享資源的向量。 該資源將在兩個向量之間共享:

// there are strings in the V2 already
std::vector<std::shared_ptr<std::string>> V1;  
std::vector<std::shared_ptr<std::string>> V2;

for (auto ptr : V2) {
    V1.push_back(ptr) // now works, ptr is a std::shared_ptr<std::string>
}

如果您無法更改V2的類型怎么辦? 然后,您必須以不同的方式引用 object,例如向量的索引並在擦除元素時保持它們同步。

std::shared_ptr沒有成員 function push_back 它最多可以指向一個 object(或自 C++17 起的數組)。

如何將字符串推送到 shared_ptr 的向量中?

像這樣:

std::string some_string;
std::vector<std::shared_ptr<std::string>> ptrs;
ptrs.push_back(std::make_shared<std::string>(some_string));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM