Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

map::equal_range

公众成员函数  <map>
pair<const_iterator,const_iterator> equal_range (const key_type& k) const;
pair<iterator,iterator>             equal_range (const key_type& k);

获取相等元素的范围

返回一个范围的边界,该范围包括容器中键值等于k的所有元素。

因为map容器中的所有元素都是唯一的键,所以返回的范围最多只包含一个元素。

如果没有找到匹配项,则返回的范围长度为0,根据容器的内部比较对象(key_comp), 两个迭代器都指向第一个键在k之后的元素。

如果容器的比较对象返回false,则认为两个键是等价的(即,无论键作为参数传递的顺序如何)。

☲  参数


K
要搜索的键。
成员类型key_type是容器中元素的类型,在map中定义为其第一个模板参数(Key)的别名。

☉  返回值



该函数返回一个pair,其成员pair::first是范围的下界 (与lower_bound相同),pair::second是范围的上界(与upper_bound相同)。
如果map对象是const限定的,则该函数返回一对const_iterator。否则,它返回一对iterator.
成员类型iteratorconst_iterator是指向元素(value_type类型)的双向迭代器类型。
注意,map容器中的value_type本身也是一个pair类型: pair<const key_type, mapped_type>

☣  示例



// map::equal_range
#include <iostream>
#include <map>

int main ()
{
  std::map<char,int> mymap;

  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;

  std::pair<std::map<char,int>::iterator,std::map<char,int>::iterator> ret;
  ret = mymap.equal_range('b');

  std::cout << "lower bound points to: ";
  std::cout << ret.first->first << " => " << ret.first->second << '\n';

  std::cout << "upper bound points to: ";
  std::cout << ret.second->first << " => " << ret.second->second << '\n';

  return 0;
}

输出:
lower bound points to: 'b' => 20
upper bound points to: 'c' => 30

✥ 复杂度



size 对数.

☣ 迭代器的有效性



不变.

⇄ 数据竞争


访问容器(const和非const版本都不会修改容器)。
不访问映射值:并发访问或修改元素是安全的。

☂ 异常安全性



强保证:如果抛出异常,容器中不会有任何变化。

🍄  另请参阅



map::lower_bound 返回迭代器下界(公众成员函数)
map::upper_bound 返回迭代器上界(公众成员函数)
map::find 获取元素迭代器(公众成员函数)
map::count 具有特定值的元素数量(公众成员函数)
map::operator[] 访问元素(公众成员函数)

联系我们 免责声明 关于CandCplus 网站地图