C++/C--二分查找之lower_bound( )和upper_bound( )【轉載】

1 頭文件及相關函數

頭文件: #include <algorithm>

二分查找的函數有 3 個: 參考:C++ lower_bound 和upper_bound

  • lower_bound(起始地址,結束地址,要查找的數值) 返回的是數值 第一個 出現的位置。

  • upper_bound(起始地址,結束地址,要查找的數值) 返回的是數值 最後一個 出現的位置。

  • binary_search(起始地址,結束地址,要查找的數值) 返回的是是否存在這麼一個數,是一個bool值

2 函數lower_bound()

功能:函數lower_bound()在first和last中的前閉後開區間進行二分查找,返回大於或等於val的第一個元素位置。如果所有元素都小於val,則返回last的位置.

注意: 如果所有元素都小於val,則返回last的位置,且last的位置是越界的!!

3 函數upper_bound()

功能: 函數upper_bound()返回的在前閉後開區間查找的關鍵字的上界,返回大於val的第一個元素位置。

注意:返回查找元素的最後一個可安插位置,也就是“元素值>查找值”的第一個元素的位置。同樣,如果val大於數組中全部元素,返回的是last。(注意: 數組下標越界)。

PS:

    lower_bound(val):返回容器中第一個值【大於或等於】val的元素的iterator位置。

    upper_bound(val): 返回容器中第一個值【大於】val的元素的iterator位置。

4 示例

代碼實現:

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

using namespace std;

int main(int argc,char** argv)
{
	vector<int> t;
	t.push_back(4);
	t.push_back(5);
	t.push_back(6);
	t.push_back(7);
	t.push_back(8);
	t.push_back(9);
	t.push_back(10);


	int low = lower_bound(t.begin(), t.end(), 5) - t.begin();
	int upp = upper_bound(t.begin(), t.end(), 5) - t.begin();
	//bool res = binary_search(t.begin(), t.end(), 5);//結果爲1
	cout << low << endl;
	cout << upp << endl;

	system("pause");
	return 0;
}

運行結果:
在這裏插入圖片描述
參考:

  1. STL之std::set、std::map的lower_bound和upper_bound函數使用說明
  2. https://blog.csdn.net/jadeyansir/article/details/77015626 可以多看幾遍
  3. https://blog.csdn.net/tjpuacm/article/details/26389441
  4. https://blog.csdn.net/lanzhihui_10086/article/details/43269511

以上內容來自:

  1. 唐的糖_C++ lower_bound 與 upper_bound 函數【CNBOLGS】
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章