2015-12-26 21 views
7

私は地元のstd::vector<std::reference_wrapper<T> >を持って、今、私はその要素の(すなわちがstd::vector<T>)を本当のコピーを返すようにしたいです。ループよりも良い方法がありますか?<はstd :: reference_wrapper <T>>はstd ::ベクトルします<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; 
} 

答えて

8

それはそう、明白なアプローチは、ちょうど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()); 
} 
1

あなたはstd::copyこの方法を使用することができます。

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

copyOfLocals.reserve(refsToLocals.size())を呼び出す使用してください。コピーとヒープ割り当てを最小限に抑えます。

関連する問題