Namaran

Code daily. Without assist.

2026-10-18

score_band.cpp

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores = {50, 60, 60, 70, 80, 80, 90};
    auto first = scores.begin();
    auto last = scores.end();
    std::cout << std::upper_bound(first, last, 80) - std::lower_bound(first, last, 60) << '\n';
    std::cout << std::lower_bound(first, last, 80) - std::upper_bound(first, last, 60) << '\n';
}

これは何を出力するでしょうか?

Answer

5 と 1 の2行です。

lower_bound(first, last, x) は x 以上の最初の要素を、upper_bound(first, last, x) は x より大きい最初の要素を指します。scores の添字で数えると、lower_bound(60) は最初の 60 の添字 1、upper_bound(80) は 90 の添字 6 なので、1行目は 6 - 1 = 5 です。数えたのは 60、60、70、80、80 で、60点以上80点以下、両端を含む閉区間(closed interval)[60, 80] にある人数になります。

2行目は2つの関数を入れ替えています。upper_bound(60) は 70 の添字 3、lower_bound(80) は最初の 80 の添字 4 で、4 - 3 = 1 です。数えたのは 70 だけで、60点より上で80点未満、両端を含まない開区間(open interval)(60, 80) の人数です。

下端を含めるなら lower_bound、含めないなら upper_bound を使い、上端を含めるなら upper_bound、含めないなら lower_bound を使います。両端で別々に選べるので、60点以上80点未満のような片側だけ含む区間も同じ形で数えられます。