将指针std :: list转换为值std :: list的快速方法 [英] Fast way to convert std::list of pointer to std::list of value

查看:166
本文介绍了将指针std :: list转换为值std :: list的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 std :: list< obj *> ,其中 obj 是我的课程:

I have a std::list<obj*>, where obj is my class:

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

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


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

I want to convert this list to the equivalent std::list<obj>, after that I no longer need the list_of_ptr.

What is the fastest way to do this work?

推荐答案

std :: transform 是您的朋友:

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表达式,则可以使用一个简单的函数对象来执行间接操作:

Or, if C++11 lambda expressions cannot be used, one may use a simple function object to perform the indirection:

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 中的指针所指向的对象的生存期。

These, of course, assume that there are no null pointers in the sequence. It is left as an exercise for the reader to figure out how to correctly manage the lifetimes of the objects pointed to by the pointers in list_of_ptr.

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

Ideally, one would use a std::vector<obj> from the start, or, if that is not possible, a container of smart pointers. Manually managing the lifetimes of the pointed-to objects, and doing so correctly, is very difficult. C++ has awesome automatic object lifetime management facilities (destructors, smart pointers, containers, stack semantics, RAII), and there is no reason not to use them.

这篇关于将指针std :: list转换为值std :: list的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆