std::vector
この場合から始めますがstd::vector
、質量の突然変異に2番目を使用しreserve()
、次にswap()
ベクトルを使用します。
アップデート
これは次の一般的な形式を取ります。
std:vector<t_object*> source; // << source already holds 10000 elements
std:vector<t_object*> tmp;
// to minimize reallocations and frees to 1 and 1, if possible.
// if you do not swap or have to grow more, reserving can really work against you.
tmp.reserve(aMeaningfulReserveValue);
while (performingMassMutation) {
// "i scan through each element and lets every 20 elements"
for (twentyElements)
tmp.push_back(source[readPos++]);
// "every 20 elements i'll need to insert an new element"
tmp.push_back(newElement);
}
// approximately 500 iterations later…
source.swap(tmp);
Borealidは、測定という良い点を提起しました。実行は、stdライブラリの実装、データサイズ、コピーの複雑さなどによって大幅に異なります。
私の構成では、このサイズのコレクションの生のポインターの場合、vector
マスミューテーションpush_back
以上はstd::list
挿入よりも7倍高速でした。の範囲挿入push_back
よりも速かった。vector
Emileが以下で指摘するように、std::vector::swap()
要素を移動したり再割り当てしたりする必要はありません。内部を交換するだけです(アロケータが同じタイプの場合)。