45項 count、find、binary_search、lower_bound、upper_bound、およびequal_rangeの違いを理解しよう

count、find、binary_search、lower_bound、upper_bound、およびequal_rangeの違いを理解しよう



本書にまとまった表が載っていたので、引用します。


何を知りたいか
使用するアルゴリズム使用するメンバ関数
未ソートの範囲ソート済みの範囲setまたはmapmultisetまたはmultimap
必要な値が存在するかfindbinary_searchcountfind
必要な値の最初の位置findequal_rangefindfindまたはlower_bound
必要な値以上の値の最初の位置find_iflower_boundlower_boundlower_bound
必要な値より大きい値の最初の位置find_ifupper_boundupper_boundupper_bound
必要な値の数countequal_rangecountcount
必要な値のすべての位置find(繰り返し)equal_rangeequal_rangeequal_range

必要な値が存在するかを調べるのにcountを使っているのは、setが要素の重複を許さないため、countの戻り値が1か0かで存在を調べられるからです。

multisetまたはmultimapの必要な値の最初の位置を調べるとき、同じ値が複数存在すると、findの返す要素が最初の要素であるという保証はありません。
同じ値が複数存在する可能性があるときは、lower_boundを使います。