【问题标题】:How to push a string into a vector of shared_ptr?如何将字符串推送到 shared_ptr 的向量中?
【发布时间】:2019-10-17 18:38:59
【问题描述】:

如果我有一个共享指针向量 (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 中的字符串吗?

【问题讨论】:

  • 本例中的type 是什么?
  • 指针,无论智能与否,都不是容器。你真正想做什么?你想解决什么问题?您是否想要一个指向V2 中元素的指针向量?为什么?同样,您需要解决的问题(真正的和原始的问题)是什么?
  • 指向什么的共享指针向量?
  • V1 甚至不是向量
  • @HuangMolly:请提供MVCE。现在你让人们猜测你想要实现什么。

标签: c++ vector iterator shared-ptr


【解决方案1】:

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 的类型怎么办?然后您必须以不同的方式引用对象,例如向量的索引并在擦除元素时保持它们同步。

【讨论】:

  • 因为 V1 是不同的类型,即 . std::vector> 所以我不能直接做 push_back 。
  • 啊!然后它改变了一切。但我不知道你想做什么......为什么你想让std::shared_ptr&lt;SImplementation&gt;指向std::string?你想创建新的SImplementation,它具有字符串值或类似的东西,还是你真的希望一种类型引用另一种类型的对象?
  • 我希望 V1 中的 shared_ptr 指向 V2 中的字符串,但它们是不同的类型。所以这真的让我很困惑。
  • @HuangMolly 好吧,它不能。你不能因为 int* int_ptr = new std::string 不能编译的同样原因。可悲的是,这没有意义。
【解决方案2】:

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));

【讨论】:

  • 我忘记为 V1 做矢量类型了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 2014-06-15
  • 2021-12-10
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 2023-03-06
相关资源
最近更新 更多