7

I have a local std::vector<std::reference_wrapper<T> > and now I want to return a real copy of its 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;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
Dmytrii S.
  • 231
  • 2
  • 4
  • 11

2 Answers2

8

It seems, the obvious approach is to just construct a std::vector<T> from a sequence from the 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());
}
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
1

You could use std::copy this way:

std::copy(
    refsToLocals.begin(), 
    refsToLocals.end(), 
    std::back_inserter(copyOfLocals));

Be sure to use call copyOfLocals.reserve(refsToLocals.size()). It will minimize copies and heap-allocations.

Curve25519
  • 654
  • 5
  • 17