unordered_multimap :: equal_range()是C++ STL中的内置函数,该函数返回所有元素的键都等于key的范围。它返回一对迭代器,其中第一个是指向范围下限的迭代器,第二个是指向范围上限的迭代器。如果容器中没有等于给定值的元素,则它将返回一对上下限都指向容器末端或unordered_multimap.end()之后的位置的对。
句法:
unordered_multimap_name.equal_range(k)
参数:该函数接受强制性参数k 。返回的范围将包含键为k的元素。
返回值:返回一对迭代器。
下面的程序说明了上述函数:
程序1:
// C++ program to illustrate the
// unordered_multimap::equal_range()
#include
#include
using namespace std;
int main()
{
// declaration
unordered_multimap 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
#include
using namespace std;
int main()
{
// declaration
unordered_multimap 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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。