47
std::vector<int> a;
std::vector<int> b;
std::vector<int> c;

bcの要素を に追加して、これら 3 つのベクトルを連結したいと思いaます。これを行うための最良の方法はどれですか?またその理由は?


1)を使用してvector::insert:

a.reserve(a.size() + b.size() + c.size());
a.insert(a.end(), b.begin(), b.end());
a.insert(a.end(), c.begin(), c.end());
b.clear();
c.clear();

2)を使用してstd::copy:

a.reserve(a.size() + b.size() + c.size());
std::copy(b.begin(), b.end(), std::inserter(a, a.end()));
std::copy(c.begin(), c.end(), std::inserter(a, a.end()));
b.clear();
c.clear();

3)std::move(から)を使用してC++11

a.reserve(a.size() + b.size() + c.size());
std::move(b.begin(), b.end(), std::inserter(a, a.end()));
std::move(c.begin(), c.end(), std::inserter(a, a.end()));
b.clear();
c.clear();
4

4 に答える 4

20

移動せずにコピーしたい場合、これが最善の方法です。

a.reserve(a.size()+b.size()+c.size()); // Reserve space first
a.insert(a.end(),b.begin(),b.end());
a.insert(a.end(),c.begin(),c.end());

移動したい場合:

a.reserve(a.size()+b.size()+c.size()); // Reserve space first
a.insert(a.end(),std::make_move_iterator(b.begin()),
         std::make_move_iterator(b.end()));
a.insert(a.end(),std::make_move_iterator(c.begin()),
         std::make_move_iterator(c.end()));
b.swap(std::vector<int>()); // Clear and deallocate space
c.swap(std::vector<int>()); // Clear and deallocate space

更新: 質問を何度か編集して、やや動くターゲットにしています。あなたの最初のオプションは、私の最初の提案と非常に似ています。

更新 2 : C++11 の時点で、ライブラリvector. 以下は、より直感的な方法でジョブを実行できます。

// Empty the vectors of objects
b.clear(); 
c.clear();

// Deallocate the memory allocated by the vectors 
// Note: Unlike the swap trick, this is non-binding and any space reduction
//       depends on the implementation of std::vector
b.shrink_to_fit();
c.shrink_to_fit();
于 2013-08-09T13:12:50.860 に答える
0

vectorbとのデータを本当に追加したい場合は、挿入を行う必要があります (これは実際には1. です)。ca

a.reserve( a.size() + b.size() + c.size() ); // preallocate memory (see why)
a.insert( a.end(), b.begin(), b.end() );
a.insert( a.end(), c.begin(), c.end() );

std::copyコンパイラ(あなたの2. )に応じて、通常は同じくらい高速である必要があります。

aは常にメモリ内で連続している必要があるため、 (C++11 で定義されているように)移動std::vectorすることはできず、最終サイズがわかっている場合は、ベクトルを予約する必要があります (ベクトルの不要な再割り当てを回避できます)。しかし、本当にパフォーマンスが心配な場合は、これを 3つにして、データを読み取る必要があるときにそれらを反復処理してください。std::vector

于 2013-08-09T13:17:09.587 に答える