C++ STL 中的 upper_bound() 函数映射
在本文中,我们将讨论 C++ STL 中 map::upper_bound() 函数的工作原理、语法和示例。
什么是 C++ STL 中的 Map?
Map 是关联容器,有助于存储由键值和映射值组成的元素,并按特定顺序排列。在 map 容器中,数据始终借助其关联键以内部方式进行排序。通过其唯一键访问 map 容器中的值。
什么是 map::upper_bound()?
map::upper_bound() 函数是 C++ STL 中的内置函数,在中定义
语法
Map_name.upper_bound(key& k);
参数
此函数仅接受 1 个参数 -
- k - 我们想要搜索的键。
返回值
此函数返回指向键‘k’的下一元素的迭代器,该元素被视为在键 k 之后。
示例
输入
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3; newmap.upper_bound(b);
输出
c:3
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({5, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
cout<<"\nTP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.rbegin(); i!= TP_Map.rend(); i++) {
cout << i->first << "\t" << i->second << endl;
}
auto i = TP_Map.upper_bound(2);
cout << "The upper bound of key 2 is ";
cout << i->first << " " << i->second << endl;
auto i_1 = TP_Map.upper_bound(3);
cout << "The upper bound of key 3 is ";
cout << i_1->first << " " << i_1->second << endl;
return 0;
}输出
TP Map is: MAP_KEY MAP_ELEMENT 5 50 4 70 2 30 1 10 The upper bound of key 2 is 4 :70 The upper bound of key 3 is 4 :70
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP