C++ multimap::lower_bound() 函数



C++ 的 std::multimap::lower_bound() 函数用于返回一个迭代器,该迭代器指向 multimap 中第一个键不小于指定键 (k) 的元素。这意味着它指向第一个等于或大于 k 的元素。如果未找到这样的元素,则它返回一个指向 multimap 末尾的迭代器。此函数的时间复杂度是对数的,即 O(log n)。

语法

以下是 std::multimap::lower_bound() 函数的语法。

iterator lower_bound (const key_type& k); const_iterator lower_bound (const key_type& k) const;

参数

  • k - 表示要搜索的键。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

此函数返回指向第一个元素的迭代器。

示例

让我们看下面的例子,我们将演示 lower_bound() 函数的使用。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a; a.insert({1, "Hi"}); a.insert({2, "Hello"}); a.insert({3, "Vanakam"}); auto x = a.lower_bound(2); if (x != a.end()) { std::cout << "Lower bound key value: " << x->second << std::endl; } return 0; }

输出

以上代码的输出如下:

Lower bound key value: Hello

示例

考虑以下示例,我们将对不存在的键应用 lower_bound() 并观察输出。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = { {5, "AB"}, {6, "BC"}, {4, "CD"} }; auto x = a.lower_bound(1); if (x != a.end()) { std::cout << "Lower bound key value : (" << x->first << ", " << x->second << ")\n"; } else { std::cout << "Key not found.\n"; } return 0; }

输出

以下是以上代码的输出:

Lower bound key value : (4, CD)

示例

在下面的示例中,我们将使用 lower_bound() 获取指向第一个元素的迭代器,然后遍历 multimap 的其余部分,打印所有键大于或等于下界键的元素。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = { {1, "Audi"}, {2, "RS5"}, {3, "Cruze"}, {3, "Sail"}, {4, "Beats"} }; auto x = a.lower_bound(3); std::cout << "Elements with lower bound key \n"; for (; x != a.end(); ++x) { std::cout << "(" << x->first << ", " << x->second << ")\n"; } return 0; }

输出

如果我们运行以上代码,它将生成以下输出:

Elements with lower bound key 
(3, Cruze)
(3, Sail)
(4, Beats)
multimap.htm
广告