lower_bound & upper_bound

#include<bits/stdc++.h>
using namespace std;

int main(){
    vector<int> v={1,2,3,4,5};
    auto p = lower_bound(v.begin(),v.end(),3);
    cout<<*p<<endl;
    auto q = upper_bound(v.begin(),v.end(),3);
    cout<<*q<<endl;
    return 0;
}

#include <iostream>     // std::cout

include <algorithm> // std::lower_bound

include <vector> // std::vector

using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:

bool operator()(const int&amp; i, const int&amp; j) {

    cout &lt;&lt; "=== i: " &lt;&lt; i &lt;&lt; " === j: " &lt;&lt; j &lt;&lt; "\n" ;


    return i &gt; j;
}

};
int main() {

int a[5] = { 1,2,3,4,5 };
//从 a 数组中找到第一个不小于 3 的元素
int* p = lower_bound(a, a + 5, 3);
cout &lt;&lt; "*p = " &lt;&lt; *p &lt;&lt; endl;
vector&lt;int&gt; myvector{ 4,5,3,1,2 };
//根据 mycomp2 规则,从 myvector 容器中找到第一个违背 mycomp2 规则的元素
vector&lt;int&gt;::iterator iter = lower_bound(myvector.begin(), myvector.end(), 3, mycomp2());
cout &lt;&lt; "*iter = " &lt;&lt; *iter;
return 0;

}

#include <iostream>     // std::cout

include <algorithm> // std::upper_bound

include <vector> // std::vector

using namespace std;
//以普通函数的方式定义查找规则
bool mycomp(int i, int j) { return i > j; }
//以函数对象的形式定义查找规则
class mycomp2 {
public:

bool operator()(const int&amp; i, const int&amp; j) {
    cout &lt;&lt; "=== i: " &lt;&lt; i &lt;&lt; " === j: " &lt;&lt; j &lt;&lt; "\n";
    return i &gt; j;
}

};
int main() {

int a[5] = { 1,2,3,4,5 };
//从 a 数组中找到第一个大于 3 的元素
int* p = upper_bound(a, a + 5, 3);
cout &lt;&lt; "*p = " &lt;&lt; *p &lt;&lt; endl;
vector&lt;int&gt; myvector{ 4,5,3,1,2 };
//根据 mycomp2 规则,从 myvector 容器中找到第一个违背 mycomp2 规则的元素
vector&lt;int&gt;::iterator iter = upper_bound(myvector.begin(), myvector.end(), 3, mycomp2());
cout &lt;&lt; "*iter = " &lt;&lt; *iter;
return 0;

}

C++ lower_bound() upper_bound() 函数用法详解(深入了解,一文学会)-CSDN博客

发表评论