c++自带的查找函数

news/2025/2/1 22:48:01/

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


http://www.ppmy.cn/news/1085238.html

相关文章

Web3 solidity编写cancelorder取消订单函数 并梳理讲述逻辑

上文 Web3 solidity订单池操作 中 我们讲述了订单池的基本概念 并手动编写了创建订单的操作 最近的 我们还是先将 ganache 环境起起来 然后 我们打开项目 上文中 我们写了makeOrder创建订单的函数 但是 也带出一个问题 我们创建之后 如果不要了 怎么干掉呀&#xff1f; js中我…

log日志

日志 1.1 作用&#xff1a; ​ 跟输出语句一样&#xff0c;可以把程序在运行过程中的详细信息都打印在控制台上。 ​ 利用log日志还可以把这些详细信息保存到文件和数据库中。 1.2 使用步骤&#xff1a; ​ 不是java的&#xff0c;也不是自己写的&#xff0c;是第三方提供…

【Linux】JumpServer 堡垒机远程访问

文章目录 前言1. 安装Jump server2. 本地访问jump server3. 安装 cpolar内网穿透软件4. 配置Jump server公网访问地址5. 公网远程访问Jump server6. 固定Jump server公网地址 前言 JumpServer 是广受欢迎的开源堡垒机&#xff0c;是符合 4A 规范的专业运维安全审计系统。JumpS…

Linux安装MySQL5.7.26教程图解

0、准备工作 下载MySQL软件包 ①、官网下载&#xff1a;https://www.cnblogs.com/linu-x/p/15701479.html#_label6 ②、百度网盘下载&#xff1a;百度网盘 请输入提取码 提取码&#xff1a;chao ③、文件说明 主机名 CentOS版本 MySQL版本 IP地址 test CentOS Linux …

MySQL的内置函数复合查询内外连接

文章目录 内置函数时间函数字符串函数数学函数其他函数 复合查询多表笛卡尔积自连接在where中使用子查询多列子查询在from中使用子查询 内连接外连接左外连接右外连接 内置函数 时间函数 函数描述current_date()当前日期current_time()当前时间current_timestamp()当前时间戳…

c语言---指针

指针 前言 记录一个数据对象在内存中的存储位置&#xff0c;需要两个信息&#xff1a; 1、数据对象的首地址。 2、数据对象占用存储空间大小 基础数据类型所占内存空间大小&#xff08;字节&#xff09;&#xff0c;一个字节代表8个二进制位 char 1 short 2 int 4 lon…

03_nodjs_npm的使用

03 【npm的使用】 1.包和npm 1.1 什么是包 由于 Node 是一套轻内核的平台&#xff0c;虽然提供了一系列的内置模块&#xff0c;但是不足以满足开发者的需求&#xff0c;于是乎出现了包&#xff08;package&#xff09;的概念&#xff1a; 与核心模块类似&#xff0c;就是将一…

websocket基础

下面就以代码来进行说明 1&#xff0c;先导入websocket依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency> 2.编写websocket相关bean管理配置 Config…