一、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; //truecout << binary_search(numList2, numList2 + 5, n1) << endl; //false//返回值为物理地址,因此要获得对应的逻辑地址,需要减去数组的起始位置。cout << lower_bound(numList1, numList1 + 5, n1)- numList1 << endl; //1cout << upper_bound(numList1, numList1 + 5, n1)- numList1 << endl; //2cout << lower_bound(numList2, numList2 + 5, n1)- numList2<< endl; //1cout << 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";}elsecout << pos - numList2; //返回下标
字符串的find
string str = "abcd";if (find(str.begin(), str.end(), 'a') != str.end())//使用迭代器cout << "Find it!";elsecout << "Couldn't find it!";// 或者string str = "abcd";cout << str.find('a');//返回的是下标的值而不是上面的指针或是迭代器