gpt4 book ai didi

c++ - 将 std::list 指针转换为 std::list 值的快速方法

转载 作者:太空狗 更新时间:2023-10-29 20:15:56 25 4
gpt4 key购买 nike

我有一个 std::list<obj*> , 其中obj是我的类(class):

std::list<obj*> list_of_ptr;
list_of_ptr.push_back(new obj());

我想将此列表转换为等效的 std::list<obj> ,之后我不再需要 list_of_ptr .

完成这项工作最快的方法是什么?

最佳答案

std::transform是你的 friend :

std::vector<obj> objects;
std::transform(
list_of_ptr.begin(), list_of_ptr.end(),
std::back_inserter(objects),
[](obj* p) { return *p; });

或者,如果不能使用 C++11 lambda 表达式,可以使用一个简单的函数对象来执行间接寻址:

struct indirect
{
template <typename T>
T& operator()(T* p) { return *p; }
};

std::transform(
list_of_ptr.begin(), list_of_ptr.end(),
std::back_inserter(objects),
indirect());

或者,使用 boost::indirect_iterator :

std::vector<obj> objects(
boost::make_indirect_iterator(list_of_ptr.begin()),
boost::make_indirect_iterator(list_of_ptr.end()));

当然,这些假设序列中没有空指针。留给读者的练习是弄清楚如何正确管理 list_of_ptr 中的指针指向的对象的生命周期。 .

理想情况下,人们会使用 std::vector<obj>从一开始,或者,如果不可能的话,一个智能指针的容器。手动管理指向对象的生命周期并正确执行此操作非常困难。 C++ 有很棒的自动对象生命周期管理工具(析构函数、智能指针、容器、堆栈语义、RAII),没有理由不使用它们。

关于c++ - 将 std::list 指针转换为 std::list 值的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11335457/

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