gpt4 book ai didi

c++ - 如何将 vector> 复制到独立 vector

转载 作者:行者123 更新时间:2023-11-30 00:47:06 26 4
gpt4 key购买 nike

我有一个 std::vector<std::unique_ptr<T>> vec1其中 T 是抽象类型。我想创建 std::vector<T*> vec2其中,第二个 vector 的指针指向的对象是第一个 vector 的指针指向的对象的拷贝。

例如:*(vec1[0]) == *(vec2[0])vec1[0].get() != vec2[0] ……等等……

怎么做?

最佳答案

使用 std::transform

std::vector<T*> vec2;
vec2.reserve(vec1.size()); // optimization to avoid reallocations, it isn't necessary, and without it the code still works correctly
std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2), [](const std::unique_ptr<T>& p){ return YourCloneFunction(*p); }

编写克隆函数的一种方法是让所有后代类都定义了虚拟 clone函数,在 T 中是抽象的.这种方法的代码很简单,但需要为每个Derived定义一次。类。

class T
{
virtual std::unique_ptr<T> clone() const = 0;
virtual ~T(){}
};

class Derived : public T
{
std::unique_ptr<T> clone() const override {
return std::unique_ptr<T>(new Derived(*this));
}
};

有了这个,代码就变成了

std::vector<T*> vec2;
vec2.reserve(vec1.size()); // optimization to avoid reallocations, it isn't necessary, and without it the code still works correctly
std::transform(vec1.begin(), vec1.end(), std::back_inserter(vec2), [](const std::unique_ptr<T>& p){ return p->clone().release(); }

注意我们有 vec2指向不属于任何智能指针的对象的原始指针。这很糟糕,除非你通过 vec2进入拥有这些指针所有权的遗留函数。

否则,如果您只想要一个 std::vector<T*>查看拷贝,克隆到中间std::vector<std::unique_ptr<T>> , 然后复制 .get() 的结果在每个实例上到 std::vector<T*>

关于c++ - 如何将 vector<unique_ptr<T>> 复制到独立 vector<T*>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35855380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com