C++ STL 中的 multimap find()


在本文中,我們將討論 C++ STL 中 multimap::find() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 Multimap?

Multimap 是關聯容器,類似於 map 容器。它也方便以特定順序儲存由鍵值和對映值組合而成的元素。在 multimap 容器中,可以有多個元素與同一個鍵關聯。資料在內部始終藉助其關聯的鍵進行排序。

什麼是 multimap::find()?

multimap::find() 是 C++ STL 中的內建函式,定義在 <map> 標頭檔案中。find() 搜尋容器中與鍵 K 關聯的元素。此函式返回指向容器中單個元素的迭代器。如果在容器中找到元素,則返回一個迭代器。

語法

iterator multimap_name.find(key);

引數

它接受一個引數 key,該引數指定要在容器中搜索的鍵。

返回值

此函式返回一個迭代器,該迭代器指向容器中鍵所在的位置。

輸入

multimap<char, int > newmap;
newmap.insert(make_pair(‘A’, 22));
newmap.insert(make_pair(‘B’, 78));
newmap.insert(make_pair(‘C’, 66));
newmap.insert(make_pair(‘D’, 81));
newmap.insert(make_pair(’E’, 43));
newmap.find(‘D’);

輸出

81

輸入

multimap<char, int > newmap;
newmap.insert(make_pair(1, 15));
newmap.insert(make_pair(2, 18));
newmap.insert(make_pair(3, 45));
newmap.insert(make_pair(4, 66));
newmap.find(4);

輸出

66

可以遵循的方法

  • 首先,我們初始化 Map。

  • 然後,我們插入帶有 Key 的元素。

  • 然後,我們使用 mapfind 函式 () 查詢 Key 的位置。

  • 然後,我們列印所需的鍵及其元素。

使用上述方法,我們可以找到容器中的任何鍵,我們也可以找到鍵在範圍內的位置。

示例

#include<iostream.h>
#include<map.h>
Using namespace std;
int main( ){
   Multimap<char, int> mp;
   / / inserting the element
   mp.insert({‘b’, 23});
   mp.insert({‘a’, 46});
   mp.insert({‘c’, 78});
   mp.insert({‘e’, 11});
   mp.insert({‘d’, 34});
   cout<< “ The Key value after key c : \n” ;
   cout<< “ Key\t Element”;
   for(auto i = mp.find(‘c’); i != mp.end( ); i++)
      cout<<i-first<< “\t” << i->second << ‘\n’;
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出

KEY ELEMENT
c 78
d 34
e 11

示例

#include<iostream.h>
#include<map.h>
Using namespace std;
int main( ){
   Multimap<char, int> mp;
   / / inserting the element
   mp.insert({‘1’, 33});
   mp.insert({‘2’, 66});
   mp.insert({‘3’, 55});
   mp.insert({‘4’, 11});
   mp.insert({‘5’, 44});
   cout<< “ The Key value after key 4 : \n” ;
   cout<< “ Key\t Element”;
   for(auto i = mp.find(‘4’); i != mp.end( ); i++)
      cout<<i-first<< “\t” << i->second << ‘\n’;
   return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出

KEY ELEMENT
4 11
5 44

更新於:2020年8月13日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告