c++自帶的查找函數詳解
一、binary_search
使用binary_search查找必須是排好序的才行。使用下面三個函數都需要先排一遍序
//這三個函數都有三個參數:分別為數組的起始位置、數組的終止位置(取不到)以及要查找的目標值,
lower_bound():返回大于或等于目標值的第一個位置
upper_bound():返回大于目標值的第一個位置
//返回值為物理地址,因此要獲得對應的邏輯地址,需要減去數組的起始位置。
binary_search():若目標值存在則返回true,否則返回false
可以看到,下面的numList2沒有排好序,導致三個函數的返回值都是錯誤的。
#include<iostream> #include<algorithm> using namespace std; int main() { /*排好序的*/ int numList1[5] = { 1,2,3,4,5 }; int n1 = 2; /*亂序的*/ int numList2[5] = { 1,3,2,4,5 }; int n2 = 2; cout << binary_search(numList1, numList1 + 5, n1) << endl; //true cout << binary_search(numList2, numList2 + 5, n1) << endl; //false //返回值為物理地址,因此要獲得對應的邏輯地址,需要減去數組的起始位置。 cout << lower_bound(numList1, numList1 + 5, n1)- numList1 << endl; //1 cout << upper_bound(numList1, numList1 + 5, n1)- numList1 << endl; //2 cout << lower_bound(numList2, numList2 + 5, n1)- numList2<< endl; //1 cout << upper_bound(numList2, numList2 + 5, n1) - numList2 << endl; //3 }
二、find
即便不排序也可以正常用。
數組的find
/*亂序的*/ int numList2[5] = { 1,3,2,4,5 }; int n2 = 2; int* pos = find(numList2, numList2 + 5, 2); //若找到,則返回物理地址,需要減去首地址以獲得下標 if (pos == (numList2 + 5)) { cout << "Couldn't find it"; } else cout << pos - numList2; //返回下標
字符串的find
string str = "abcd"; if (find(str.begin(), str.end(), 'a') != str.end()) //使用迭代器 cout << "Find it!"; else cout << "Couldn't find it!"; // 或者 string str = "abcd"; cout << str.find('a'); //返回的是下標的值而不是上面的指針或是迭代器
到此這篇關于c++自帶的查找函數的文章就介紹到這了,更多相關c++查找函數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++11 std::shared_ptr總結與使用示例代碼詳解
這篇文章主要介紹了C++11 std::shared_ptr總結與使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06