C ++中的std :: binary_search()

binary_search()作為STL函數 (binary_search() as a STL function)

Syntax:

句法:

bool binary_search (
ForwardIterator first, 
ForwardIterator last, 
const T& value);

Where,

哪里,

  • ForwardIterator first = iterator to start of the range

    ForwardIterator first =迭代器開始范圍

  • ForwardIterator last =iterator to end of the range

    ForwardIterator last =迭代器到范圍的結尾

  • T &value = reference to searching element which is of datatype T, T can be any inbuilt datatype or user-defined data type

    T&value =對數據類型為T的搜索元素的引用, T可以是任何內置數據類型或用戶定義的數據類型

Return type: bool

返回類型: bool

  • True - if element found in the range

    True-如果在范圍內找到元素

  • False - If the element not found in the range

    False-如果在范圍內找不到元素

The above syntax is used to compare elements using standard comparison operators. Two elements a & b are said to be equal if (!(a<b) && !(a>b)).

上面的語法用于使用標準比較運算符比較元素。 if(!(a <b)&&!(a> b))的兩個元素ab相等。

We can also define the user-defined comparator for comparing. The syntax with user-defined comparator is like below:

我們還可以定義用戶定義的比較器進行比較。 用戶定義的比較器的語法如下:

bool binary_search(
ForwardIterator first, 
ForwardIterator last, 
const T& val, 
Comparator comp);

Using the above syntax two elemnts a & b would be equal if (!comp(a<b) && !comp(a>b)).

使用以上語法, 如果(!comp(a <b)&&!comp(a> b)),則兩個元素a和b相等。

1)使用默認比較器 (1) Using default comparator)

#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr{ 3, 2, 1, 4, 5, 6, 7 };
//tp perform binary search we need sorted 
//input array
sort(arr.begin(), arr.end());
int search_element = 4;
//ForwardIterator first=arr.begin()
//ForwardIterator last=arr.end()
//const T& val=search_element
if (binary_search(arr.begin(), arr.end(), search_element)) {
cout << "search_element " << search_element << " found\n";
}
else
cout << "search_element" << search_element << " not found\n";
search_element = 7;
//ForwardIterator first=arr.begin()
//ForwardIterator last=arr.begin()+arr.size()-1
//const T& val=search_element
if (binary_search(arr.begin(), arr.begin() + arr.size() - 1, search_element)) {
cout << "search_element " << search_element << " found\n";
}
else
cout << "search_element " << search_element << " not found\n";
return 0;
}

Output:

輸出:

search_element 4 found
search_element 7 not found

In the above program, we have checked to cases and have used the default comparator. No need to mention, since this uses the binary search algorithm for searching, we need to feed sorted array only.

在上面的程序中,我們檢查了案例并使用了默認的比較器。 無需提及,因為它使用二進制搜索算法進行搜索,所以我們僅需要提供已排序的數組。

So as a pre-requisite we sorted the array. The sorted array is: [1,2,3,4,5,6,7]

因此,作為前提條件,我們對數組進行了排序。 排序后的數組是: [1,2,3,4,5,6,7]

Then for the first case, our range is the entire vector, and it returned true is since it finds the searched element 4.

那么對于第一種情況,我們的范圍是整個向量,并且由于找到了要搜索的元素4而返回true。

For the second case, our range is [1-6] as we mentioned the end iterator as arr.begin()+arr.size()-1 which leaves the last element 7. So searched element 7 is not found.

對于第二種情況,我們的范圍是[1-6],因為我們提到的最終迭代器為arr.begin()+ arr.size()-1 ,它保留了最后一個元素7 。 因此未找到搜索到的元素7

2)使用用戶定義的比較器功能 (2) Using user-defined comparator function)

Here we have taken a use case where we have student details for five students. By using the user-defined comparator we have checked whether there is a student with the specified marks or not.

在這里,我們使用了一個用例,其中有五個學生的學生詳細信息。 通過使用用戶定義的比較器,我們檢查了是否有指定分數的學生。

#include <bits/stdc++.h>
using namespace std;
class student {
int score;
int roll;
string name;
public:
student()
{
score = 0;
roll = 0;
name = "";
}
student(int sc, int ro, string nm)
{
score = sc;
roll = ro;
name = nm;
}
int get_score()
{
return score;
}
int get_roll()
{
return roll;
}
string get_name()
{
return name;
}
};
//comparator for sorting
bool myfunc(student a, student b)
{
if (a.get_score() < b.get_score()) //no swap
return true;
else //swap
return false;
}
//comparator for binary search
//match found if !mycomp(a,b) && !mycomp(b,a)
bool mycomp(student a, student b)
{
if (a.get_score() < b.get_score())
return true;
return false;
}
int main()
{
vector<student> arr(5);
//1st student
arr[0] = student(80, 5, "XYZ"); //roll 5, marks 80
//2nd student
arr[1] = student(70, 10, "INC"); //roll 10, marks 70
//3rd student
arr[2] = student(85, 7, "HYU"); //roll 7, marks 85
//4th student
arr[3] = student(83, 1, "EFG"); //roll 1,  marks 83
//5th student
arr[4] = student(81, 11, "ABC"); //roll 11,  marks 81
//sort based on marks
//user-defined compartor=myfunc to sort
sort(arr.begin(), arr.end(), myfunc);
//find if any student exists who scored 81
student t1(81, -1, ""); //dummy search element just to search the student marks
if (binary_search(arr.begin(), arr.end(), t1, mycomp))
cout << "Student with marks 81 exists\n";
else
cout << "Student with marks 81 doesn't exist\n";
//find if any student exists who scored 75
student t2(75, -1, ""); //dummy search element just to search the student marks
if (binary_search(arr.begin(), arr.end(), t2, mycomp))
cout << "Student with marks 75 exists\n";
else
cout << "Student with marks 75 doesn't exist\n";
return 0;
}

Output:

輸出:

Student with marks 81 exists
Student with marks 75 doesn't exist

Here we have first sorted the student vector using the user-defined comparator function. We have defined a separate comparator for binary search, though both have the same body. We have specified just to underline the factor that both comparators are not used in the same way. In case of searching, there is a match b/w T a and T b (T be the datatype) if !comp(a,b) && !comp(b, a) where a is element from the vector and b is the searching element.

在這里,我們首先使用用戶定義的比較器函數對學生向量進行了排序。 我們為二進制搜索定義了一個單獨的比較器,盡管兩者具有相同的主體。 我們僅指定要強調兩個比較器未以相同方式使用的因素。 在搜索的情況下, 如果!comp(a,b)&&!comp(b,a)匹配b / w T a和T b(T為數據類型) 其中a是向量中的元素, b是搜索元素。

So in this article, you saw how efficiently we can use binary_search to search elements within a range, no matter what kind of object it is. Even for the user-defined datatype, we can do by using a user-defined comparator as shown above. But, the main thing to remember is that the input list must be sorted(based on the key). For example, as we were searching for the marks, we sorted the student list based on marks.

因此,在本文中,您看到了無論使用哪種對象,我們都能有效地使用binary_search搜索范圍內的元素。 即使對于用戶定義的數據類型,我們也可以通過使用用戶定義的比較器來完成,如上所示。 但是,要記住的主要事情是必須對輸入列表進行排序(基于鍵)。 例如,在搜索標記時,我們根據標記對學生列表進行了排序。

翻譯自: https://www.includehelp.com/stl/std-binary_search-in-cpp.aspx

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540724.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540724.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540724.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HNUSTOJ-1437 無題

1437: 無題 時間限制: 1 Sec 內存限制: 128 MB提交: 268 解決: 45[提交][狀態][討論版]題目描述 tc在玩一個很無聊的游戲&#xff1a;每一次電腦都會給一個長度不超過10^5的字符串&#xff0c;tc每次都從第一個字符開始&#xff0c;如果找到兩個相鄰相一樣的字符&#xff0c;…

凱撒密碼pythin密碼_凱撒密碼術

凱撒密碼pythin密碼Caesar cipher is one of the well-known techniques used for encrypting the data. Although not widely used due to its simplicity and being more prone to be cracked by any outsider, still this cipher holds much value as it is amongst the fir…

MultiQC使用指導

MultiQC使用指導 官網資料文獻&#xff1a;MultiQC --- summarize analysis results for multiple tools and samples in a single report參考資料一&#xff1a; 整合 fastq 質控結果的工具 簡介 MultiQC 是一個基于Python的模塊, 用于整合其它軟件的報告結果, 目前支持以下軟…

FYFG的完整形式是什么?

FYFG&#xff1a;對您的未來指導 (FYFG: For Your Future Guidance) FYFG is an abbreviation of "For Your Future Guidance". FYFG是“ For your Future Guidance”的縮寫 。 It is an expression, which is commonly used in the Gmail platform. It is also wr…

WorkerMan 入門學習之(二)基礎教程-Connection類的使用

一、TcpConnection類 的使用 1、簡單的TCP測試 Server.php <?php require_once __DIR__./Workerman/Autoloader.php; use Workerman\Worker; $worker new Worker(websocket://0.0.0.0:80);// 連接回調 $worker->onConnect function ($connection){echo "connecti…

kotlin獲取屬性_Kotlin程序獲取系統名稱

kotlin獲取屬性The task is to get the system name. 任務是獲取系統名稱。 package com.includehelpimport java.net.InetAddress/*** Function for System Name*/fun getSystemName(): String? {return try {InetAddress.getLocalHost().hostName} catch (E: Exception) {S…

71文件類型

1.kit類型 標準的SeaJs模塊文件類型&#xff0c;直接對外暴露方法。 2.units類型 依賴pageJob&#xff0c;對外暴露一個名字&#xff0c;pageJob依賴暴露的名字對模塊進行初始化&#xff0c;在pageJob內部邏輯自動執行init方法&#xff1b; 由于沒有對外暴露方法&#xff0c;只…

ruby 生成哈希值_哈希 Ruby中的運算符

ruby 生成哈希值In the last article, we have seen how we can carry out a comparison between two hash objects with the help of "" operator? "" method is a public instance method defined in Ruby’s library. 在上一篇文章中&#xff0c;我們看…

七牛大數據平臺的演進與大數據分析實踐--轉

原文地址&#xff1a;http://www.infoq.com/cn/articles/qiniu-big-data-platform-evolution-and-analysis?utm_sourceinfoq&utm_mediumpopular_widget&utm_campaignpopular_content_list&utm_contenthomepage 七牛大數據平臺的演進與大數據分析實踐 (點擊放大圖像…

最大化切割段

Description: 描述&#xff1a; In this article we are going to review classic dynamic programing problem which has been featured in interview rounds of amazon. 在本文中&#xff0c;我們將回顧在亞馬遜的采訪輪次中已經介紹的經典動態編程問題。 Problem statemen…

響應數據傳出(springMVC)

1. SpringMVC 輸出模型數據概述 提供了以下幾種途徑輸出模型數據&#xff1a; ModelAndView: 處理方法返回值類型為 ModelAndView 時, 方法體即可通過該對象添加模型數據 Map 及 Model: 入參為 org.springframework.ui.Model、 org.springframework.ui.ModelMap 或 java.uti…

python 字母順序計數_計數并說出順序

python 字母順序計數Problem statement: 問題陳述&#xff1a; The count-and-say sequence is the sequence of integers with the first five terms as following: 計數序列是具有前五個項的整數序列&#xff0c;如下所示&#xff1a; 1 1個 11 11 21 21 1211 1211 111221 …

微信網頁掃碼登錄的實現

為了讓用戶登錄網站的門檻更低&#xff0c;微信掃一掃登錄變得越來越廣泛&#xff0c;所以最近加緊趕制的項目中有用到這個功能&#xff0c;此篇文字的出發點基于微信開放平臺已經配置好域名&#xff08;80端口&#xff09;并且認證成功獲得app_id和secret并有權限調用微信的接…

希爾密碼_希爾密碼| 網絡安全

希爾密碼Now, Hill Cipher is a very basic cryptographic technique which is used to convert a string into ciphertext. This technique was invented by an American Mathematician "Lester Sanders Hill". This is a polygraphic substitution cipher because …

Android 那些年,處理getActivity()為null的日子

在日常開發中的時候&#xff0c;我們經常會使用ViewPagerFragment進行視圖滑動&#xff0c;在某些部分邏輯也許我們需要利用上下文Context&#xff08;例如基本的Toast&#xff09;&#xff0c;但是由于Fragment只是衣服在Activity容器的一個試圖&#xff0c;如果需要拿到當前的…

設計模式狀態模式uml_UML的完整形式是什么?

設計模式狀態模式umlUML&#xff1a;統一建模語言 (UML: Unified Modeling Language) UML is an abbreviation of Unified Modeling Language. In the field of software engineering, it is a visual modeling language that is standard in quality. It makes it available t…

idea debug快捷鍵

idea的debug調試快捷鍵 F9 resume programe 恢復程序 AltF10 show execution point 顯示執行斷點 F8 Step Over 相當于eclipse的f6 跳到下一步 F7 Step Into 相當于eclipse的f5就是 進入到代碼 AltshiftF7 Force Step Into 這個…

vqa mcb_MCB的完整形式是什么?

vqa mcbMCB&#xff1a;微型斷路器 (MCB: Miniature Circuit Breaker) MCB is an abbreviation of "Miniature Circuit Breaker". MCB是“微型斷路器”的縮寫 。 It is an automatically operated electronics switch. It is designed to detect the fault in the e…

返回表達式列表中最小值least(exp1,exp2,exp3,……,expn)

1 least(exp1,exp2,exp3,……,expn)2 【功能】返回表達式列表中值最小的一個。如果表達式類型不同&#xff0c;會隱含轉換為第一個表達式類型。3 【參數】exp1……n&#xff0c;各類型表達式4 【返回】exp1類型5 6 【示例】7 SELECT least(10,32,123,2006) FROM dual;8 9 SEL…

Java Short類hashCode()方法及示例

短類hashCode()方法 (Short class hashCode() method) hashCode() method is available in java.lang package. hashCode()方法在java.lang包中可用。 hashCode() method is used to return hashcode of the Short object.hashCode()方法用于返回Short對象的哈希碼。 hashCode(…