std::vector
から目的の項目を完全に削除する良い方法は、erase-remove というイディオムであると一般に理解されています。
上記のリンクに記載されているように (この投稿の日付の時点で)、コードでは、消去と削除のイディオムは次のようになります。
int main()
{
// initialises a vector that holds the numbers from 0-9.
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// erase-remove idiom to completely eliminate the desired items from the vector
v.erase( std::remove( std::begin(v), std::end(v), 5 ), std::end(v) );
}
resize-remove
イディオムが機能とパフォーマンスの点でイディオムと同等かどうかを知りたいerase-remove
です。または、おそらく私は明らかな何かを見逃していますか?
次のresize-remove
イディオムは上記のイディオムと同等erase-remove
ですか?
int main()
{
std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Is this "resize-remove" approach equivalent to the "erase-remove" idiom?
v.resize( std::remove( std::begin(v), std::end(v), 5 ) - v.begin() );
}