C++的Find算法用法,

在 C++ 中,可以使用 std::map 统计值出现次数为 2 的键。具体步骤如下:

  1. 遍历 std::map,找出所有值为 2 的键。
  2. 使用条件语句检查每个值,符合条件时记录对应键。
#include <iostream>
#include <map>
#include <vector>int main() {// 创建一个 std::map 并插入数据std::map<int, int> data = {{1, 2}, {2, 3}, {3, 2}, {4, 1}, {5, 2}};// 用于存储值为 2 的键std::vector<int> keys_with_value_2;// 遍历 mapfor (const auto& pair : data) {if (pair.second == 2) {keys_with_value_2.push_back(pair.first);}}// 输出统计结果std::cout << "Keys with value 2:" << std::endl;for (int key : keys_with_value_2) {std::cout << key << " ";}std::cout << std::endl;return 0;
}

示例运行结果

如果 data 中的内容是 {{1, 2}, {2, 3}, {3, 2}, {4, 1}, {5, 2}},输出结果为:

Keys with value 2: 1 3 5

关键点

  1. std::map 的有序性std::map 会根据键自动排序,但这不影响统计值的逻辑。
  2. 复杂度:遍历 std::map 的复杂度为 O(n),其中 n 为键值对的数量。

如果需要统计这些键的数量,可以直接输出 keys_with_value_2.size()

在 C++ 中,std::set 是一个有序且不允许重复元素的集合,常用来存储不重复的数据并支持快速查找、插入和删除操作。

以下是关于 std::set 的详细介绍和常用操作:


定义和初始化

#include <iostream>
#include <set>int main() {// 创建一个空的 setstd::set<int> s;// 初始化 setstd::set<int> s2 = {1, 3, 5, 7};// 输出初始化的内容for (int x : s2) {std::cout << x << " ";}return 0;
}

主要特点

  1. 有序性std::set 自动按照键的顺序存储元素(默认升序)。
  2. 唯一性std::set 不允许存储重复的元素。
  3. 底层实现std::set 是基于红黑树的有序集合,支持对数时间复杂度的插入、删除和查找操作。

常用操作

1. 插入元素

std::set<int> s; s.insert(5); s.insert(3); s.insert(8); s.insert(3); // 重复插入 3,会被忽略

2. 遍历集合

for (int x : s) { std::cout << x << " "; } // 或使用迭代器 for (auto it = s.begin(); it != s.end(); ++it) { std::cout << *it << " "; }

3. 删除元素

s.erase(3); // 删除元素 3 s.erase(s.begin()); // 删除第一个元素

4. 查找元素

if (s.find(5) != s.end()) {

std::cout << "Found 5" << std::endl; } else { std::cout << "5 not found" << std::endl; }

5. 获取集合大小

std::cout << "Size: " << s.size() << std::endl;

6. 检查集合是否为空

if (s.empty()) { std::cout << "Set is empty" << std::endl; }


更多高级操作

1. 获取范围内的元素
std::set<int> s = {1, 3, 5, 7, 9};
auto itLow = s.lower_bound(3); // 返回指向第一个 >= 3 的迭代器
auto itUp = s.upper_bound(7); // 返回指向第一个 > 7 的迭代器for (auto it = itLow; it != itUp; ++it) {std::cout << *it << " ";
}
2. 合并两个集合
std::set<int> s1 = {1, 3, 5};
std::set<int> s2 = {2, 4, 6};// 插入另一个集合的所有元素
s1.insert(s2.begin(), s2.end());for (int x : s1) {std::cout << x << " ";
}


示例代码

 
#include <iostream>
#include <set>int main() {std::set<int> s = {4, 2, 8, 6};// 插入元素s.insert(5);s.insert(3);// 遍历元素std::cout << "Set elements: ";for (int x : s) {std::cout << x << " ";}std::cout << std::endl;// 查找元素if (s.find(3) != s.end()) {std::cout << "3 is found in the set" << std::endl;} else {std::cout << "3 is not found in the set" << std::endl;}// 删除元素s.erase(3);// 检查集合大小std::cout << "Set size: " << s.size() << std::endl;return 0;
}


运行结果

Set elements: 2 4 5 6 8 3 is found in the set Set size: 4

总结

std::set 是一个非常实用的 STL 容器,适用于需要保持元素唯一且有序的场景。如果需要存储重复元素,可以考虑使用 std::multiset

C++算法库中的find如何使用

在 C++ 中,std::find 是一个用于在容器中查找某个值的通用算法,定义在 <algorithm> 头文件中。它可以用来查找 std::vectorstd::liststd::array 等标准容器中的某个值。


std::find 的用法

Iterator find(Iterator first, Iterator last, const T& value);

  • 参数说明

    1. firstlast:容器的起始迭代器和结束迭代器,表示查找范围 [first, last)
    2. value:要查找的值。
  • 返回值

    • 如果找到值,则返回指向该值的迭代器。
    • 如果未找到值,则返回 last 迭代器。

使用示例

1. 在 std::vector 中查找
 
#include <iostream>
#include <vector>
#include <algorithm> // std::findint main() {std::vector<int> vec = {1, 2, 3, 4, 5};// 查找值 3auto it = std::find(vec.begin(), vec.end(), 3);if (it != vec.end()) {std::cout << "Found " << *it << " at index " << (it - vec.begin()) << std::endl;} else {std::cout << "Value not found" << std::endl;}return 0;
}

输出

Found 3 at index 2


2. 在 std::list 中查找
#include <iostream>
#include <list>
#include <algorithm>int main() {std::list<int> lst = {10, 20, 30, 40, 50};// 查找值 30auto it = std::find(lst.begin(), lst.end(), 30);if (it != lst.end()) {std::cout << "Found " << *it << std::endl;} else {std::cout << "Value not found" << std::endl;}return 0;
}
 

输出

Found 30


3. 查找字符串中的字符

std::find 也可以用来查找字符串中的某个字符。

#include <iostream>
#include <string>
#include <algorithm>int main() {std::string str = "hello world";// 查找字符 'o'auto it = std::find(str.begin(), str.end(), 'o');if (it != str.end()) {std::cout << "Found '" << *it << "' at index " << (it - str.begin()) << std::endl;} else {std::cout << "Character not found" << std::endl;}return 0;
}

输出

Found 'o' at index 4


其他注意事项

  1. 查找的范围是 [first, last)

    • std::find 不会检查 last,因此传递的范围必须有效。
  2. 对于自定义类型的查找

    • 如果容器中存储的是自定义类型,需要重载 == 运算符,std::find 才能正常工作。

示例:在自定义类型中查找
 
#include <iostream>
#include <vector>
#include <algorithm>struct Point {int x, y;// 重载 == 运算符bool operator==(const Point& other) const {return x == other.x && y == other.y;}
};int main() {std::vector<Point> points = {{1, 2}, {3, 4}, {5, 6}};Point target = {3, 4};auto it = std::find(points.begin(), points.end(), target);if (it != points.end()) {std::cout << "Found Point(" << it->x << ", " << it->y << ")" << std::endl;} else {std::cout << "Point not found" << std::endl;}return 0;
}

输出

Found Point(3, 4)


性能和复杂度

  • 时间复杂度:O(n),其中 n 是容器中的元素数量。
  • 空间复杂度:O(1)

对于大容器,如果需要频繁查找,可以考虑使用 std::unordered_setstd::unordered_map,它们提供平均时间复杂度为 O(1) 的查找性能。


总结

  1. std::find 是一个通用的查找算法,适用于所有支持迭代器的容器。
  2. 它使用线性搜索,适合中小型容器。
  3. 对于自定义类型,要确保实现了 == 运算符。

在 C++ 中,std::find 通常不适用于 std::mapstd::unordered_map,因为这些容器存储的是键值对 (std::pair<const Key, Value>),而不是单一的值。如果要在 std::map 中查找某个键或值,通常需要使用 std::map 提供的专用方法,如 find 或迭代器。


std::map 中查找键

std::map 自带的 find 函数更高效(时间复杂度为 O(log n)),可以直接查找键,而不需要用 <algorithm> 中的 std::find

示例:
#include <iostream>
#include <map>int main() {std::map<int, std::string> m = {{1, "one"}, {2, "two"}, {3, "three"}};// 使用 map 自带的 find 函数查找键 2auto it = m.find(2);if (it != m.end()) {std::cout << "Found key: " << it->first << ", value: " << it->second << std::endl;} else {std::cout << "Key not found" << std::endl;}return 0;
}

输出

Found key: 2, value: two

使用 std::find_if 查找键

如果你必须使用 <algorithm> 中的 std::find 系列函数,可以通过 std::find_if 自定义谓词来查找键。

#include <iostream>
#include <map>
#include <algorithm>int main() {std::map<int, std::string> m = {{1, "one"}, {2, "two"}, {3, "three"}};// 使用 std::find_if 查找键int key_to_find = 2;auto it = std::find_if(m.begin(), m.end(), [key_to_find](const std::pair<int, std::string>& p) {return p.first == key_to_find; // 比较键});if (it != m.end()) {std::cout << "Found key: " << it->first << ", value: " << it->second << std::endl;} else {std::cout << "Key not found" << std::endl;}return 0;
}


std::map 中查找值

std::map 的设计是以键为主查找值。如果想要查找某个值,则需要遍历整个 map,例如用 std::find_if 来查找。

示例:用 std::find_if 查找值
 
#include <iostream>
#include <map>
#include <algorithm>int main() {std::map<int, std::string> m = {{1, "one"}, {2, "two"}, {3, "three"}};// 使用 std::find_if 查找值 "two"auto it = std::find_if(m.begin(), m.end(), [](const std::pair<int, std::string>& p) {return p.second == "two";});if (it != m.end()) {std::cout << "Found value: " << it->second << ", key: " << it->first << std::endl;} else {std::cout << "Value not found" << std::endl;}return 0;
}

输出

Found value: two, key: 2


查找键值对

如果需要查找完整的键值对(std::pair),可以直接使用 std::find

 
#include <iostream>
#include <map>
#include <algorithm>int main() {std::map<int, std::string> m = {{1, "one"}, {2, "two"}, {3, "three"}};// 查找键值对 {2, "two"}auto it = std::find(m.begin(), m.end(), std::make_pair(2, "two"));if (it != m.end()) {std::cout << "Found pair: {" << it->first << ", " << it->second << "}" << std::endl;} else {std::cout << "Pair not found" << std::endl;}return 0;
}

输出

Found pair: {2, two}


总结

  • 查找 :使用 map::find,效率更高,O(log n)
  • 查找 :可以使用 std::find_if 遍历容器。
  • 查找完整的 键值对:可以直接用 std::find

如果需要频繁查找值,建议使用 std::multimap 或维护一个反向映射的辅助数据结构(如 std::unordered_map<Value, Key>

auto it = std::find(m.begin(), m.end(), std::make_pair(2, "two"));

auto 的类型

it 的类型是 std::map<int, std::string>::iterator,也就是 std::map 的迭代器类型。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/888771.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

《鸟哥的Linux私房菜基础篇》---4 Linux档案的压缩与打包

目录 一、常见的压缩包的扩展名 二、常见的压缩和解压指令 1、tar 2、tar gzip&#xff08;.tar.gz&#xff09; (或 .tgz) 3、tar bzip2&#xff08;.tar.bz2&#xff09; 4、zip 5、gzip 6、bzip2 7、xz 8、rar 9、7z 三、安装解压工具 一、常见的压缩包的扩展…

基于springboot的音乐网站的设计与实现

文末获取源码和万字论文&#xff0c;制作不易&#xff0c;感谢点赞支持。 音乐网站 摘要 随着信息技术在管理上越来越深入而广泛的应用&#xff0c;管理信息系统的实施在技术上已逐步成熟。本文介绍了音乐网站的开发全过程。通过分析音乐网站管理的不足&#xff0c;创建了一个计…

【软考速通笔记】系统架构设计师⑲——专业英语

文章目录 一、前言二、常用名词三、架构风格四、非功能需求五、应用架构六、软件架构重用 一、前言 笔记目录大纲请查阅&#xff1a;【软考速通笔记】系统架构设计师——导读 二、常用名词 名词翻译architecture架构system系统design设计requirements需求components组件constr…

三菱JET伺服CC-Link IE现场网络Basic链接软元件(RYn/RXn)(RWwn/RWrn)

链接软元件(RYn/RXn) 要点 在循环通信中对主站发送给伺服放大器的请求(RYn及RWwn)设定了范围外的值时&#xff0c;将无法反映设定内容。 循环通信的请求报文与响应报文的收发数据被换读为伺服放大器的对象数据(RYn、RXn)。 响应报文的设定值可进行变更。变更初始设定值时&…

WPF中的VisualState(视觉状态)

以前在设置控件样式或自定义控件时&#xff0c;都是使用触发器来进行样式更改。触发器可以在属性值发生更改时启动操作。 像这样&#xff1a; <Style TargetType"ListBoxItem"><Setter Property"Opacity" Value"0.5" /><Setter …

ARINC 标准全解析:航空电子领域多系列标准的核心内容、应用与重要意义

ARINC标准概述 ARINC标准是航空电子领域一系列重要的标准规范&#xff0c;由航空电子工程委员会&#xff08;AEEC&#xff09;编制&#xff0c;众多航空公司等参与支持。这些标准涵盖了从飞机设备安装、数据传输到航空电子设备功能等众多方面&#xff0c;确保航空电子系统的兼…

用golang简单做一个内网穿透小工具!

一个个人需求&#xff0c;需要简单的穿透一下 家里的电脑&#xff0c;也不需要多稳定&#xff0c;也没有并发。然后 通过http可以访问到内网的 一个网站&#xff0c; 因为服务端 是linux 系统 &#xff0c;内网是 windows10服务器 所以 就采用 用golang这个语言来实现&#xff…

Android Studio 历史版本下载

Android Studio 历史版本下载 官方链接&#xff1a;https://developer.android.google.cn/studio/archive 通过gradle插件版本反查Android Studio历史版本 Android Studio Ladybug | 2024.2.1 October 1, 2024 【https://redirector.gvt1.com/edgedl/android/studio/ide-zip…

微服务监控prometheus+Grafana

目录 Prometheus 概述 核心组件 特点 使用场景 Grafana 概述 功能特点 使用场景 PrometheusGrafana组合 部署和配置 一、准备工作 二、部署Prometheus 三、部署Grafana 四、创建监控仪表盘 五、验证和调优 总结 微服务监控是确保微服务架构稳定运行的关键环节…

(vue)el-cascader多选级联选择器,值取最后一级的数据

(vue)el-cascader多选级联选择器&#xff0c;取值取最后一级的数据 获取到&#xff1a;[“养殖区”,“鸡棚”,“E5001”] 期望&#xff1a;[“E5001”] 问题: 解决方法 增加change事件方法&#xff0c;处理选中的value值 1.单选 <el-cascaderv-model"tags2":o…

Java设计模式之状态模式架构高扩展的订单状态管理

🧑 博主简介:CSDN博客专家,历代文学网(PC端可以访问:https://literature.sinhy.com/#/literature?__c=1000,移动端可微信小程序搜索“历代文学”)总架构师,15年工作经验,精通Java编程,高并发设计,Springboot和微服务,熟悉Linux,ESXI虚拟化以及云原生Docker和K8s…

独立ip服务器有什么优点?

网站的性能和安全性直接影响到用户体验和业务发&#xff0c;独立IP服务器作为一种主流的托管方式&#xff0c;因其独特的优势而受到许多企业和个人站长的青睐。与共享IP相比&#xff0c;独立IP服务器到底有哪些优点呢&#xff1f; 使用独立IP的用户不必担心与其他网站共享同一…

深入理解MySQL中的ONLY_FULL_GROUP_BY

在MySQL数据库管理中&#xff0c;ONLY_FULL_GROUP_BY是一个重要的SQL模式&#xff0c;它直接影响着GROUP BY语句的执行方式和结果。本文将从基础概念出发&#xff0c;逐步解析ONLY_FULL_GROUP_BY的工作原理、应用场景及应对策略。 什么是ONLY_FULL_GROUP_BY&#xff1f; ONLY…

图论理论基础和存储方式的实现

图论1 图论 (Graph theory) 是数学的一个分支&#xff0c;图是图论的主要研究对象。图 (Graph) 是由若干给定的顶点及连接两顶点的边所构成的图形&#xff0c;这种图形通常用来描述某些事物之间的某种特定关系。顶点用于代表事物&#xff0c;连接两顶点的边则用于表示两个事物…

每日一练 | Diff-Serv在QoS配置中的应用

01 真题题目 通常在配置 QoS 中的 Diff-Serv 时,边界路由器会通过报文的源地址和目的地址等对报文 进行分类,对不开的报文设置不同的IP优先级,而其他路由器只需要根据IP优先来对报文进行 识别即可 A.正确 B.错误 02 真题答案 A 03 答案解析 在基于 Diff-Serv&#xff08;Diff…

macOS运行amd64的镜像

在macOS上运行amd64&#xff08;x86_64&#xff09;架构的镜像&#xff0c;通常通过虚拟化或仿真工具来实现。例如&#xff0c;如果你使用的是基于Apple Silicon&#xff08;M1或M2等&#xff09;芯片的Mac&#xff0c;那么你的处理器是ARM架构的&#xff0c;而amd64是x86架构&…

Git常用的命令【提交与回退】

git分布式版本控制系统 &#xff08;SVN集中式版本控制系统&#xff09;之间的对比 git有本地仓库和远程仓库&#xff0c;不同的开发人员可以分别提交自己的本地仓库并维护代码的版本控制。 然后多个人员在本地仓库协作的代码&#xff0c;可以提交到远程仓库中做整合。 git本…

AUTOSAR AP和CP的安全要求规范(Safety Req)详细解读

一、规范的编制的背景原因 编制该规范的原因 确保系统安全性和可靠性 随着汽车电子系统日益复杂&#xff0c;功能不断增加&#xff0c;对安全性和可靠性的要求也越来越高。该规范为AUTOSAR平台在安全执行、配置、更新、信息交换、数据处理等多方面制定了明确要求&#xff0c;…

黑马程序员MybatisPlus/Docker相关内容

Day01 MP相关知识 1. mp配置类&#xff1a; 2.条件构造器&#xff1a; 具体的实现例子&#xff1a; ①QuerryWapper&#xff1a; ②LambdaQueryWrapper: 3.MP的自定义SQL 4.MP的Service层的实现 5.IService下的Lambda查询 原SQL语句的写法&#xff1a; Lambda 查询语句的…