C++ multimap equal_range()

2024年8月30日 | 阅读4分钟

C++ multimap equal_range() 函数用于返回容器中所有键元素等于 x 的范围的边界。

如果 x 不匹配容器中的任何键,则返回值的范围长度为 0,并且两个迭代器都将指向大于 x 的最近值。否则,如果 x 大于容器中的所有元素,它将指向 end。

语法

该范围由两个迭代器定义。它返回包含容器中所有键等同于 k 的元素的范围的边界。

参数

k:要在 multimap 容器中搜索的键。

返回值

此函数返回一个 pair。其中 pair::first 是范围的下边界,与 lower_bound(x) 返回的值相同,pair::second 是与 upper_bound(x) 返回的值相同的范围上边界。

复杂度

大小的对数。

迭代器有效性

无变化。

数据竞争

容器被访问(const 和 non-const 版本都不会修改容器)。

不访问任何映射值:并发访问和修改元素是安全的。

异常安全

如果抛出异常,容器中没有变化。


示例 1

让我们看一个简单的例子

输出

Lower bound of b is: b = 2
Upper bound of b is: c = 3

在上面的例子中,b 的下边界是 b,b 的上边界是 c。

示例 2

让我们看一个简单的例子

输出

The lower bound is 3:0
The upper bound is 3:0

在上面的示例中,equal_range() 函数返回 0,因为它尝试查找 multimap mp 中不存在的键 10。

示例 3

让我们看一个简单的例子

输出

The lower bound of the element with a key of 2 in the multimap m1 is: 20.
The upper bound of the element with a key of 2 in the multimap m1 is: 30.
A direct call of upper_bound( 2 ) gives 30,
 matching the 2nd element of the pair returned by equal_range( 2 ).
The multimap m1 doesn't have an element with a key less than 4.

示例 4

让我们看一个简单的例子

输出

B, 1

下一个主题C++ Multimap