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');
	//返回的是下标的值而不是上面的指针或是迭代器

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ad_m1n

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值