當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ unordered_multimap find()用法及代碼示例


unordered_multimap::find()是C++ STL中的內置函數,該函數返回一個迭代器,該迭代器指向具有鍵k的元素之一。如果容器不包含鍵為k的任何元素,則它將返回一個迭代器,該迭代器指向經過容器中最後一個元素的位置。

用法:

unordered_multimap_name.find(k)

參數:該函數接受指定 key 的強製參數k。


返回值:它返回一個迭代器,該迭代器指向具有鍵k的元素所在的位置。

以下示例程序旨在說明上述函數:

示例1:

// C++ program to illustrate the 
// unordered_multimap::find() function 
#include <iostream> 
#include <unordered_map> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multimap<int, int> sample; 
  
    // inserts key and element 
    sample.insert({ 1, 2 }); 
    sample.insert({ 1, 2 }); 
    sample.insert({ 2, 3 }); 
    sample.insert({ 3, 4 }); 
    sample.insert({ 2, 6 }); 
  
    // find the element with key 1 and print 
    auto it = sample.find(1); 
    if (it != sample.end()) 
        cout << 1 << ":" << it->second << endl; 
    else
        cout << "element with key 1 not found\n"; 
  
    // find the element with 
    // key 2 and print 
    it = sample.find(2); 
    if (it != sample.end()) 
        cout << 2 << ":" << it->second << endl; 
    else
        cout << "element with key 2 not found\n"; 
  
    // find the element with 
    // key 100 and print 
    it = sample.find(100); 
    if (it != sample.end()) 
        cout << 100 << ":" << it->second << endl; 
    else
        cout << "element with key 100 not found\n"; 
    return 0; 
}
輸出:
1:2
2:6
element with key 100 not found

示例2:

// C++ program to illustrate the 
// unordered_multimap::find() 
#include <iostream> 
#include <unordered_map> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multimap<char, char> sample; 
  
    // inserts element 
    sample.insert({ 'a', 'b' }); 
    sample.insert({ 'a', 'b' }); 
    sample.insert({ 'a', 'd' }); 
    sample.insert({ 'b', 'e' }); 
    sample.insert({ 'b', 'd' }); 
  
    // find the element with 
    // key r and print 
    auto it = sample.find('r'); 
    if (it != sample.end()) 
        cout << "r"
             << ":" << it->second << endl; 
    else
        cout << "element with key r not found\n"; 
  
    // find the element with 
    // key a and print 
    it = sample.find('a'); 
    if (it != sample.end()) 
        cout << 'a' << ":" << it->second << endl; 
    else
        cout << "element with key a not found\n"; 
  
    // find the element with 
    // key 'b' and print 
    it = sample.find('b'); 
    if (it != sample.end()) 
        cout << "b"
             << ":" << it->second << endl; 
    else
        cout << "element with key b not found\n"; 
  
    return 0; 
}
輸出:
element with key r not found
a:d
b:d


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 unordered_multimap find() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。