【问题标题】:How to convert std::vector<std::reference_wrapper<T> > to std::vector<T>如何将 std::vector<std::reference_wrapper<T> > 转换为 std::vector<T>
【发布时间】:2016-03-31 18:23:47
【问题描述】:
我有一个本地的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;
}
【问题讨论】:
标签:
c++
c++11
vector
reference-wrapper
【解决方案1】:
看来,显而易见的方法是从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());
}
【解决方案2】:
你可以这样使用std::copy:
std::copy(
refsToLocals.begin(),
refsToLocals.end(),
std::back_inserter(copyOfLocals));
请务必拨打电话copyOfLocals.reserve(refsToLocals.size())。它将最小化副本和堆分配。