C++ STL库中的map::equal_range()用法

传送门 ==>> AutoSAR实战系列300讲「糖果Autosar」总目录

1 map::equal_range()

map::equal_range()是 C++ STL 中的内置函数,它返回一对迭代器。该对是指一个范围的边界,该范围包括容器中具有等效于 k 的键的所有元素。由于映射容器只包含唯一键,因此返回的对中的第一个迭代器因此指向该元素,而对中的第二个迭代器指向键 K 之后的下一个键。如果没有与键 K 匹配并且key K 大于最大 key ,返回的范围长度为 1,两个迭代器都指向一个元素,该元素的 key 表示 map 的大小,元素为 0。否则下界和上界都指向元素大于键 K。

语法: 
iterator map_name.equal_range(key)

参数:此函数接受单个强制参数键,该键指定要返回容器中其范围的元素。
返回值:该函数返回一对迭代器,如上所述。
以下程序说明了上述方法:

2 示例1

CPP

// C++ program to illustrate the
// map::equal_range() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // initialize container
    map<int, int> mp;
 
    // insert elements in random order
    mp.insert({ 4, 30 });
    mp.insert({ 1, 40 });
    mp.insert({ 6, 60 });
 
    pair<map<int, int>::iterator,
         map<int, int>::iterator>
        it;
 
    // iterator of pairs
    it = mp.equal_range(1);
    cout << "The lower bound is "
         << it.first->first
         << ":" << it.first->second;
 
    cout << "\nThe upper bound is "
         << it.second->first
         << ":" << it.second->second;
 
    return 0;
}
输出: 
The lower bound is 1:40
The upper bound is 4:30

3 示例2

CPP

// C++ program to illustrate the
// map::equal_range() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // initialize container
    map<int, int> mp;
 
    // insert elements in random order
    mp.insert({ 4, 30 });
    mp.insert({ 1, 40 });
    mp.insert({ 6, 60 });
 
    pair<map<int, int>::iterator,
         map<int, int>::iterator>
        it;
 
    // iterator of pairs
    it = mp.equal_range(10);
    cout << "The lower bound is "
         << it.first->first << ":"
         << it.first->second;
 
    cout << "\nThe upper bound is "
         << it.second->first
         << ":" << it.second->second;
 
    return 0;
}
输出: 
The lower bound is 3:0
The upper bound is 3:0
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

糖果Autosar

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

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

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

打赏作者

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

抵扣说明:

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

余额充值