public member function
<map>

std::map::find

      iterator find (const key_type& k);const_iterator find (const key_type& k) const;
查詢元素
在容器中搜索具有與 k 等效的 的元素,如果找到,則返回指向它的迭代器,否則返回指向 map::end 的迭代器。

兩個 被認為是等效的,如果容器的 比較物件 返回false自反地(即,無論元素以何種順序作為引數傳遞)。

另一個成員函式 map::count 可用於僅檢查特定鍵是否存在。

引數

k
要搜尋的鍵。
成員型別key_type是容器中元素的鍵的型別,在 map 中定義為其第一個模板引數的別名().

返回值

指向該元素的迭代器,如果找到具有指定鍵的元素,則返回,否則返回 map::end

如果 map 物件是 const 限定的,則該函式返回一個const_iterator。否則,它返回一個iterator.

成員型別iteratorconst_iterator是指向元素的(型別為value_type).
請注意,value_typemap 容器中是 pair<const key_type, mapped_type> 的別名pair<const key_type, mapped_type>.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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


複雜度

size 的對數複雜度。

迭代器有效性

沒有變化。

資料競爭

訪問容器(const 和非 const 版本都不會修改容器)。
不訪問對映值:併發訪問或修改元素是安全的。

異常安全

強保證:如果丟擲異常,容器沒有發生變化。

另見