unordered_multimap::equal_range()是C++ STL中的內置函數,該函數返回所有元素的鍵都等於鍵的範圍。它返回一對迭代器,其中第一個是指向範圍下限的迭代器,第二個是指向範圍上限的迭代器。如果容器中沒有等於給定值的元素,則它將返回一對上下限都指向容器或unordered_multimap.end()末尾的位置。
用法:
unordered_multimap_name.equal_range(k)
參數:該函數接受強製性參數k。返回的範圍將包含鍵為k的元素。
返回值:它返回一對迭代器。
以下示例程序旨在說明上述函數:
示例1:
// C++ program to illustrate the
// unordered_multimap::equal_range()
#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 });
// iterator of pairs pointing to range
// which includes 1 and print by iterating in range
auto itr = sample.equal_range(1);
cout << "Elements with Key 1: ";
for (auto it = itr.first; it != itr.second; it++) {
cout << it->second << " ";
}
cout << endl;
// iterator of pairs pointing to range
// which includes 2 and print by iterating in range
itr = sample.equal_range(2);
cout << "Elements with Key 2: ";
for (auto it = itr.first; it != itr.second; it++) {
cout << it->second << " ";
}
return 0;
}
輸出:
Elements with Key 1: 2 2 Elements with Key 2: 6 3
示例2:
// C++ program to illustrate the
// unordered_multimap::equal_range()
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
// declaration
unordered_multimap<char, char> sample;
// inserts key and element
sample.insert({ 'a', 'b' });
sample.insert({ 'a', 'b' });
sample.insert({ 'a', 'd' });
sample.insert({ 'b', 'e' });
sample.insert({ 'b', 'd' });
// iterator of pairs pointing to range
// which includes b and print by iterating in range
auto itr = sample.equal_range('b');
cout << "Elements with Key b: ";
for (auto it = itr.first; it != itr.second; it++) {
cout << it->second << " ";
}
cout << endl;
// iterator of pairs pointing to range
// which includes a and print by iterating in range
itr = sample.equal_range('a');
cout << "Elements with Key a: ";
for (auto it = itr.first; it != itr.second; it++) {
cout << it->second << " ";
}
return 0;
}
輸出:
Elements with Key b: d e Elements with Key a: d b b
相關用法
- C++ log()用法及代碼示例
- C++ div()用法及代碼示例
- C++ fma()用法及代碼示例
- C++ map key_comp()用法及代碼示例
- C++ wcsncpy()用法及代碼示例
- C++ imag()用法及代碼示例
- C++ real()用法及代碼示例
- C++ valarray end()用法及代碼示例
- C++ regex_iterator()用法及代碼示例
- C++ valarray cos()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 unordered_multimap equal_range() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。