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

std::

map::find

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

获取元素迭代器

在容器中查找键值等于k的元素,如果找到则返回该元素的迭代器,否则返回一个map::end的迭代器。

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

另一个成员函数map::count可以用来检查一个特定的键是否存在。

☲  参数


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

☉  返回值



如果找到具有指定键值的元素,则返回该元素的迭代器;否则返回map::end

如果map对象是const限定的,则函数返回const_iterator对象。否则,它返回一个iterator

成员类型iteratorconst_iterator是指向元素(value_type类型)的双向迭代器类型。 注意,映射容器中的value_typepair<const key_type, mapped_type>的别名。

☣  示例



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

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

  mymap['a']=50;
  mymap['b']=100;
  mymap['c']=150;
  mymap['d']=200;

  it = mymap.find('b');
  if (it != mymap.end())
    mymap.erase (it);

  // print content:
  std::cout << "elements in mymap:" << '\n';
  std::cout << "a => " << mymap.find('a')->second << '\n';
  std::cout << "c => " << mymap.find('c')->second << '\n';
  std::cout << "d => " << mymap.find('d')->second << '\n';

  return 0;
}

输出:
elements in mymap:
a => 50
c => 150
d => 200

✥ 复杂度



大小呈对数.

☣ 迭代器的有效性



不变.

⇄ 数据竞争


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

☂ 异常安全性



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

🍄  另请参阅



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

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