配列を表すベクトルのベクトルがあります。行を効率的に削除したい、つまり最小限の複雑さと割り当てで行を削除したい
次のように、移動セマンティクスを使用して、削除されていない行のみをコピーして、ベクトルの新しいベクトルを構築することを考えました。
//std::vector<std::vector<T> > values is the array to remove rows from
//std::vector<bool> toBeDeleted contains "marked for deletion" flags for each row
//Count the new number of remaining rows
unsigned int newNumRows = 0;
for(unsigned int i=0;i<numRows();i++)
{
if(!toBeDeleted[i])
{
newNumRows++;
}
}
//Create a new array already sized in rows
std::vector<std::vector<T> > newValues(newNumRows);
//Move rows
for(unsigned int i=0;i<numRows();i++)
{
if(!toBeDeleted[i])
{
newValues[i] = std::move(values[i]);
}
}
//Set the new array and clear the old one efficiently
values = std::move(newValues);
これが最も効果的な方法ですか?
編集:行を繰り返し下に移動することで、新しい配列の割り当てを回避できると考えました。これは少し効率的で、コードははるかに単純です。
unsigned int newIndex = 0;
for(unsigned int oldIndex=0;oldIndex<values.size();oldIndex++)
{
if(!toBeDeleted[oldIndex])
{
if(oldIndex!=newIndex)
{
values[newIndex] = std::move(values[oldIndex]);
}
newIndex++;
}
}
values.resize(newIndex);
ありがとう!