著作権:コードワードは容易ではない、ソースを明記してください。https://blog.csdn.net/qq_24309981/article/details/90581412
理論1
ファイルを含める:書式#include <アルゴリズム>
名前空間を: std名前空間を使用して、
関数テンプレートを:
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val);
template <class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val, Compare comp);
関数:イテレータ下に戻る結合(リターン部を注文最初の要素は、指定されたイテレータ値以上である; UPPER_BOUND、戻り順序付きセクション最初反復子が要素を指定した値よりも大きいです)
- 範囲内のすべての要素がヴァル未満比較する場合、機能は最後の戻りヴァル未満比較しない第1の範囲【の最初の要素を指すイテレータ、最後)を返します。
- 要素は、第二のための第1のバージョンの演算子<、およびCOMPを使用して比較しています。
- 範囲内の要素は、すでに同じ基準(オペレータ<またはCOMP)に従ってソートされなければなりません。
- 関数は、ランダムアクセスイテレータのために特別に効率的であるソート範囲の非連続的な要素を比較することにより実行される比較の数を最適化します。
- UPPER_BOUNDとは異なり、この関数によって返される反復子が指す値はまた、ヴァルに相当する、とだけでなく、大きくてもよいです。
時間計算:
- 最初と最後の間の距離の平均対数に:約LOG2(N)(Nはこの距離である)+1要素の比較を行います。
- 非ランダムアクセスイテレータでは、イテレータの進歩は、それ自身、平均してNで追加の線形複雑作り出します。
この関数テンプレートの挙動は同等です:
template <class ForwardIterator, class T>
ForwardIterator lower_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator it;
iterator_traits<ForwardIterator>::difference_type count, step;
count = distance(first,last);
while (count>0)
{
it = first; step=count/2; advance (it,step);
if (*it<val)
{ // or: if (comp(*it,val)), for version (2)
first=++it;
count-=step+1;
}
else
{
count=step;
}
}
return first;
}
例2
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
//输出
lower_bound at position 3
upper_bound at position 6