如何将 std::vector<std::reference_wrapper<T> > 转换为 std::vector<T>

How to convert std::vector<std::reference_wrapper<T> > to std::vector<T>

本文关键字:gt lt std vector 转换 reference wrapper      更新时间:2023-10-16

我有一个本地std::vector<std::reference_wrapper<T> >,现在我想返回其元素(即std::vector<T>)的真实副本。有比循环更好的方法吗?

示例:

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;
}

似乎,显而易见的方法是从std::vector<std::reference_wrapper<T>>:的序列中构建std::vector<T>

std::vector<T> foobar() {
    std::vector<std::reference_wrapper<T> > refsToLocals;
    /* do smth with refsToLocals */
    return std::vector<T>(refsToLocals.begin(), refsToLocals.end());
}

您可以这样使用std::copy

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

请务必使用呼叫copyOfLocals.reserve(refsToLocals.size())。它将最大限度地减少拷贝和堆分配。