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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。