简体   繁体   English

在 C++ 中将 shared_ptr 的向量转换为原始指针的向量

[英]Convert vector of shared_ptr into the vector of raw pointers in C++

I was wondering if there are ways to convert the vector of shared pointers into the vector of raw pointers other than doing it through the loop:我想知道是否有办法将共享指针的向量转换为原始指针的向量,而不是通过循环来做:

\\vecShared - initial vector of shared pointers
std::vector< double* > vecRaw;

for(unsigned int i=0; i<vecShared .size(); ++i)
    vecRaw.push_back(vecShared[i].get());

If there are other ways, is there an advantage of using those?如果有其他方法,使用这些方法有好处吗?

Of course当然

vecRaw.reserve(vecShared.size());
std::transform(vecShared.cbegin(), vecShared.cend(), std::back_inserter(vecRaw),
    [](auto& ptr) { return ptr.get(); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM