简体   繁体   English

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

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

If I have a vector of shared pointers (V1) and a vector which contains a lot of strings (V2).如果我有一个共享指针向量(V1)和一个包含很多字符串的向量(V2)。 How to use the shared_ptr inside of the V1 to points to the elements inside of V2?如何使用 V1 内部的 shared_ptr 指向 V2 内部的元素?

EX:前任:

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
}

Can I use a iterator something or use another shared_pointer to point to the strings in V2?我可以使用迭代器或使用另一个 shared_pointer 指向 V2 中的字符串吗?

std::shared_ptr is a tool to manage the ownership of memory. std::shared_ptr是管理 memory 所有权的工具。 The problem here is that std::vector already manages its memory.这里的问题是std::vector已经管理了它的 memory。 Also, std::vector invalidates references and pointer to its elements when resizing or erasing an element.此外,当调整或擦除元素时, std::vector会使指向其元素的引用和指针无效。

What you probably want is to have two vector of a shared resource.您可能想要的是拥有两个共享资源的向量。 That resource would be shared between the two vectors:该资源将在两个向量之间共享:

// 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>
}

What if you cannot change the type of V2 ?如果您无法更改V2的类型怎么办? Then you'll have to refer to the object in a different way, such as indices to the vector and keeping them synched when erasing elements.然后,您必须以不同的方式引用 object,例如向量的索引并在擦除元素时保持它们同步。

std::shared_ptr does not have a member function push_back . std::shared_ptr没有成员 function push_back It can point to at most one object (or an array since C++17).它最多可以指向一个 object(或自 C++17 起的数组)。

How to push a string into a vector of shared_ptr?如何将字符串推送到 shared_ptr 的向量中?

Like this:像这样:

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