C++のlower_bound関数はどんな役割を果たすのか。

C++のlower_bound関数は、順序付けられたコンテナ(例えば、vector、array、deque、setなど)の中で、挿入位置を探したり、与えられた値以上の最初の要素の位置を見つけるために使用されます。

具体に言うと、lower_bound関数は、コンテナ内で与えられた値以上の最初の要素を指すイテレーターを返します。コンテナ内に与えられた値と等しい要素が存在する場合、lower_bound関数はその要素を指すイテレーターを返します。与えられた値以上の要素が存在しない場合、lower_bound関数はコンテナの末尾を指すイテレーターを返します。

lower_bound関数の使用フォーマットは以下のとおりです:

iterator lower_bound (iterator first, iterator last, const T& val);

firstとlastは、コンテナの範囲を表すイテレータで、valは検索する値です。 lower_bound関数は、[first、last)の範囲内を検索し、val以上の最初の要素のイテレータを返します。

こちらは一つの例です。

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

int main() {
    std::vector<int> nums = {1, 3, 5, 7, 9};
    int val = 4;
    
    std::vector<int>::iterator it = std::lower_bound(nums.begin(), nums.end(), val);
    
    if (it != nums.end()) {
        std::cout << "The first element not less than " << val << " is " << *it << std::endl;
    } else {
        std::cout << "No element not less than " << val << " in the vector" << std::endl;
    }
    
    return 0;
}

結果は次の通りです:

The first element not less than 4 is 5

上記の例では、lower_bound関数は4以上の要素を検索し、5を指すイテレータを返します。

bannerAds