andreyxdd
andreyxdd

Reputation: 83

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?

Upvotes: 0

Views: 1345

Answers (1)

Flaviu
Flaviu

Reputation: 1039

Of course

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

Upvotes: 1

Related Questions