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


C++ unordered_multiset equal_range()用法及代碼示例


unordered_multiset::equal_range()是C++ STL中的內置函數,該函數返回所有元素均等於給定值的範圍。它返回一對迭代器,其中第一個是指向範圍下限的迭代器,第二個是指向範圍上限的迭代器。如果容器中沒有等於給定值的元素,則它將返回一對上下限都指向容器末端之後的位置的對。

用法:

unordered_multiset_name.equal_range(value)

參數:該函數接受要返回其範圍的元素val。


返回值:它返回一對迭代器。

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

程序1:

// C++ program to illustrate the 
// unordered_multiset::equal_range() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multiset<int> sample; 
  
    // inserts element 
    sample.insert(100); 
    sample.insert(100); 
    sample.insert(100); 
    sample.insert(200); 
    sample.insert(500); 
    sample.insert(500); 
    sample.insert(600); 
  
    // iterator of pairs pointing to range 
    // which includes 500 and print by iterating in range 
    auto itr = sample.equal_range(500); 
    for (auto it = itr.first; it != itr.second; it++) { 
        cout << *it << " "; 
    } 
  
    cout << endl; 
  
    // iterator of pairs pointing to range 
    // which includes 100 and print by iterating in range 
    itr = sample.equal_range(100); 
    for (auto it = itr.first; it != itr.second; it++) { 
        cout << *it << " "; 
    } 
  
    return 0; 
}
輸出:
500 500 
100 100 100

程序2:

// C++ program to illustrate the 
// unordered_multiset::equal_range() function 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
  
    // declaration 
    unordered_multiset<char> sample; 
  
    // inserts element 
    sample.insert('a'); 
    sample.insert('a'); 
    sample.insert('b'); 
    sample.insert('c'); 
    sample.insert('d'); 
    sample.insert('d'); 
    sample.insert('d'); 
  
    // iterator of pairs pointing to range 
    // which includes 'a' and print by iterating in range 
    auto itr = sample.equal_range('a'); 
    for (auto it = itr.first; it != itr.second; it++) { 
        cout << *it << " "; 
    } 
  
    cout << endl; 
  
    // iterator of pairs pointing to range 
    // which includes 'd' and print by iterating in range 
    itr = sample.equal_range('d'); 
    for (auto it = itr.first; it != itr.second; it++) { 
        cout << *it << " "; 
    } 
  
    return 0; 
}
輸出:
a a 
d d d


相關用法


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