如何将字符串推入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
是管理内存所有权的工具。这里的问题是std::vector
已经管理了它的内存。此外,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
类型怎么办?然后,您必须以不同的方式引用对象,例如向量的索引并在擦除元素时保持同步。
std::shared_ptr
没有成员函数push_back
。它最多可以指向一个对象(或自 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));
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 为共享 ptr 向量实现复制 c'tor?
- 对唯一 ptr 无效读取的引用向量
- 接口 PTR 的返回向量C++
- 如何在满足谓词的向量中获得唯一PTR的子集
- 通过成员函数将唯一 ptr 的向量附加到另一个向量
- C++ 提升克隆 PTR 向量
- PTR到结构体和PTR到结构体的向量的模板方法专门化