简体   繁体   中英

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). How to use the shared_ptr inside of the V1 to points to the elements inside of 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?

std::shared_ptr is a tool to manage the ownership of memory. The problem here is that std::vector already manages its memory. Also, std::vector invalidates references and pointer to its elements when resizing or erasing an element.

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 ? 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.

std::shared_ptr does not have a member function push_back . It can point to at most one object (or an array since C++17).

How to push a string into a vector of 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM