当前位置: 首页 > news >正文

STL map 的 lower_bound(x)、upper_bound(x) 等常用函数

【STL map 简介】
● STL map 是一种关联容器,存储键值对,每个键(key value)是唯一的,而值(mapped value)可以重复。构建 STL map 时,无论元素插入顺序如何,STL map 中的元素始终
按“键值”自动递增存储。STL map 中的迭代器可理解为“指针”。

#include <bits/stdc++.h>
using namespace std;

map<int,string> mp;
int idx;
string name;
int n;

int main() {
    cin>>n;
    while(n--) {
        cin>>idx>>name;
        mp.insert({idx,name});
    }

    for(auto it=mp.begin(); it!=mp.end(); it++) {
        cout<<it->first<<":"<<it->second<<endl;
    }

    return 0;
}

/*
in:
5
3 Java
1 C++
9 Python
8 R
6 SQL

out:
1:C++
3:Java
6:SQL
8:R
9:Python
*/

● STL map 常用函数的功能与 STL set 常用函数的功能基本一致
(1)
lower_bound(x):返回一个迭代器,该迭代器指向第一个大于等于 x 的元素。若无,返回 end() 得到的迭代器。
(2)
upper_bound(x):返回一个迭代器,该迭代器指向第一个大于 x 的元素。若无,返回 end() 得到的迭代器。
(3)
find(x):返回一个迭代器,该迭代器指向“键 x”所在的元素。
(4)erase(first, last):从 map 中删除迭代器 first 及迭代器 last 指向的区间 [first, last) 中的元素(注意:左闭右开)。

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int,string> mp= {{9,"a"}, {7,"b"}, {2,"c"}, {6,"d"}};
    auto first=mp.find(2);
    auto last=mp.find(7);
    mp.erase(first,last);
    for(auto it=mp.begin(); it!=mp.end(); it++) {
        cout<<it->first<<":"<<it->second<<endl;
    }
    return 0;
}

/*
output:
7:b
9:a
*/

(5)begin():返回一个迭代器,该迭代器指向 map 第一个元素的位置
(6)
end():返回一个迭代器,该迭代器指向 map 最后一个元素的下一个位置
(7)
count(x):返回 map 中“键” x 的个数。

#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int,string> mp= {{6,"apple"},{8,"banana"}};
    cout<<mp.count(6)<<endl;  //output 1
    cout<<mp.count(5)<<endl;  //output 0
    return 0;
}

由于 map 中所有“键”的个数都是唯一的,所以若 x 在 map 中,返回 1,若 x 不在 map 中,返回 0。



【参考文献】
https://cplusplus.com/reference/map/map/
https://cplusplus.com/reference/map/map/count/
https://cplusplus.com/reference/map/map/lower_bound/
https://cplusplus.com/reference/map/map/upper_bound/
https://cplusplus.com/reference/map/map/insert/
https://cplusplus.com/reference/map/map/erase/
https://cplusplus.com/reference/map/map/begin/
https://www.cnblogs.com/linxiaoxu/p/17694869.html


 

相关文章:

  • 2025年渗透测试面试题总结-长某亭科技-安全服务工程师(一面)(题目+回答)
  • Python卷积神经网络(CNN)来识别和计数不同类型的工业零件
  • 基于ssm的物资进销存(全套)
  • .net 与 Pythonnet库的使用心得
  • idea 创建springboot 项目,连接数据库,后台接口实现
  • ajax之生成一个ajax的demo示例
  • QSplitter.setStretchFactor无效
  • 分析TCP三次握手与四次挥手
  • 前沿科技展望未来发展趋势
  • 【linux网络编程】套接字socket
  • 近三年图像超分辨率研究进展综述(轻量化方向)
  • 介绍高性能的HTTP和反向代理服务器Nginx
  • hbase-05 namespace、数据的确界TTL
  • python加载动态网站内容Playwright使用介绍
  • 小程序 wxml 语法 —— 39 简单双向数据绑定
  • 力扣1463. 摘樱桃 II
  • 存量思维和增量思维
  • Python代码调试方法集锦
  • 用DEEPSEEK做数据看板:高效、实用与创新的融合
  • android paging使用教程
  • 免费虚拟空间网站/seo网站优化培训
  • 做百度手机网站点击/西安关键词seo
  • 自己可以做网站空间吗/热搜词排行榜关键词
  • wordpress 子主题开发/广州优化疫情防控举措
  • 哪个网站可以做平面兼职/营销型网站建设多少钱
  • 网站安全风险提示单/新闻热点大事件