c++ - 将指针 vector 转换为对象 vector

标签 c++ c++11 vector

我有这个 vector :

std::vector<T*> foo;

我有一个具有以下签名的函数(我无法更改它):

void bar(std::vector<T> const&);

如何以最少的更改将 foo 传递给该函数?

我目前的做法是:

std::vector<T> another_bar(bar.size());
std::transform(std::begin(bar),std::end(bar),std::begin(another_bar),[](T* item){return *T;});

我认为这里发生了很多不必要的复制。

编辑:

T 不是模板化参数。它是一个特定的类型。

最佳答案

虽然您需要对某些拷贝进行操作,但您可以避免构造默认值,然后通过直接复制构造来创建拷贝:

std::vector<T> another_bar;
another_bar.reserve(bar.size());
std::transform(std::begin(bar), std::end(bar),
               std::back_inserter(another_bar),[](T* item){return *item;});

关于c++ - 将指针 vector 转换为对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35428092/

相关文章:

c++ - 在这个 C++ TCP 客户端中,我在哪里设置 TCP_NODELAY?

C++如何检测空格

c++ - 在 C++ 中循环合法的相同 vector

R:regexpr() 如何在模式参数中使用向量

c++ - 如何处理模板类的 vector ?

c++ - C++中的堆排序

c++ - ffmpeg::avcodec_encode_video 设置 PTS h264

c++ - 模板转换函数到 const-reference

c++ - 如何在 std::array<> 上使用 std::for_each 并在每个元素上应用 lambda 函数?

c++ - 在虚析构函数中调用其他虚方法是否安全?