C++ 程序:在 STL 映射中使用lower_bound()
和upper_bound()
方法
大家好!
在本教程中,我们将学习 C++ 编程语言中 STL 中 Map 的下界()和上界()方法的工作方式。
要了解 STL 中映射容器的基本功能,我们将推荐您访问 STL 映射容器,我们从零开始详细解释了这个概念。
lower_bound()
方法:
**lower_bound()**
方法返回一个指向第一个元素的迭代器,该元素的值不小于给定值。
upper_bound()
方法:
**upper_bound()**
方法是一个迭代器,指向第一个元素,该元素的值大于给定值。
为了更好地理解它的实现,请参考下面给出的注释良好的 C++ 代码。
代号:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to demonstrate the lower_bound() and upper_bound() in Map, in CPP ===== \n\n\n";
//Map declaration (Map with key and value both as integers)
map<int, int> m;
//Filling the elements by using the insert() method.
cout << "Filling the Map with key-value pairs of integers in random order."; //Map automatically stores them in increasing order of keys
//make_pair() is used to insert a key value pair into the map
m.insert(make_pair(3, 30));
m.insert(make_pair(2, 20));
m.insert(make_pair(5, 50));
m.insert(make_pair(9, 90));
m.insert(make_pair(1, 10));
cout << "\n\nThe number of elements in the Map are: " << m.size();
cout << "\n\nThe elements of the Map m are: ";
map<int, int>::iterator i;
for (i = m.begin(); i != m.end(); i++)
{
cout << "( " << i->first << ", " << i->second << " ) ";
}
map<int, int>::iterator low, high;
//lower_bound(x) returns the iterator to the first element that is greater than or equal to element with key x
low = m.lower_bound(5);
cout << "\n\nThe lower bound of 5 has key: " << low->first << " and value: " << low->second << ". ";
low = m.lower_bound(6);
cout << "\n\nThe lower bound of 6 has key: " << low->first << " and value: " << low->second << ". ";
//upper_bound(x) returns the iterator to the first element that is greater than element with key x
high = m.upper_bound(3);
cout << "\n\nThe upper bound of 3 has key: " << high->first << " and value: " << high->second << ". ";
high = m.upper_bound(4);
cout << "\n\nThe upper bound of 4 has key: " << high->first << " and value: " << high->second << ". ";
cout << "\n\n\n";
return 0;
}
输出:
我们希望这篇文章能帮助您更好地理解 STL 中映射容器的下界()和上界()方法的概念及其在 CPP 中的实现。如有任何疑问,请随时通过下面的评论区联系我们。
继续学习: