LoginSignup
4
3

More than 1 year has passed since last update.

【C++】Erase-removeイディオム

Last updated at Posted at 2020-04-30

vectorの要素を削除したいとき。

remove

remove.cpp
vector<int> a = {1,2,3,4};
auto p = remove(a.begin(), a.end(), 2); // {1, 3, 4, 4}

[1つ目の引数, 2つ目の引数)の範囲で、3つ目の引数と一致する要素を取り除き、有効な要素を前に寄せる。
この時、vectorのサイズは変わらず不要な要素は末尾に寄せられただけとなる。
pには1つ目の4のイテレータが入る。

erase

そこでstd::vector::eraseを使う。

erase.cpp
vector<int> a = {1,2,3,4};
auto p = remove(a.begin(), a.end(), 2);
a.erase(p, a.end());

eraseでは[1つ目の引数,2つ目の引数)の範囲が削除される。
これで、後ろに寄せられた不要な要素が削除される。

Erase-removeイディオム

組み合わせてこんな感じで使う。

erase-remove.cpp
vector<int> a = {1,2,3,4};
a.erase(remove(a.begin(), a.end(), 2), a.end());

参考

https://cpprefjp.github.io/reference/algorithm/remove.html
https://cpprefjp.github.io/reference/vector/vector/erase.html
https://ja.wikibooks.org/wiki/More_C%2B%2B_Idioms/消去・削除(Erase-Remove)

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3