How to convert std :: vector <std :: reference_wrapper <T>> to std :: vector <T>
I have a local std::vector<std::reference_wrapper<T> > and now I want to return a real copy of my elements (i.e. std::vector<T> ). Is there a better way than a loop?
Example:
std::vector<T> foobar() { std::vector<std::reference_wrapper<T> > refsToLocals; /* do smth with refsToLocals */ std::vector<T> copyOfLocals; for (auto local : refsToLocals) copyOfLocals.insert_back(local.get()); return copyOfLocals; } +7
Dmytrii S.
source share2 answers
The obvious approach seems to be to simply construct a std::vector<T> from the sequence from std::vector<std::reference_wrapper<T>> :
std::vector<T> foobar() { std::vector<std::reference_wrapper<T> > refsToLocals; /* do smth with refsToLocals */ return std::vector<T>(refsToLocals.begin(), refsToLocals.end()); } +8
Dietmar KΓΌhl
source shareYou can use std::copy as follows:
std::copy( refsToLocals.begin(), refsToLocals.end(), std::back_inserter(copyOfLocals)); Be sure to use the copyOfLocals.reserve(refsToLocals.size()) call copyOfLocals.reserve(refsToLocals.size()) . This minimizes copy and heap allocation.
+1
Tal shalti
source share