C++ multimap::find() 函数



C++ 的std::multimap::find() 函数用于在 multimap 中搜索特定键。它返回一个指向键首次出现的迭代器,如果未找到则返回 end()。与 map 不同,multimap 允许重复键。它通常用于检索与特定键关联的元素,从而可以轻松访问映射到该键的所有值。此函数的时间复杂度是对数的,即 O(log n)。

语法

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

iterator find (const key_type& k); const_iterator find (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.

返回值

如果找到具有特定键的元素,则此函数返回指向该元素的迭代器。

示例

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

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{1, "A"}, {2, "B"}, {3, "C"}}; auto x = a.find(1); if (x != a.end()) { std::cout << "Key Found : " << x->second << std::endl; } else { std::cout << "Key Not Found." << std::endl; } return 0; }

输出

以上代码的输出如下:

Key Found : A

示例

考虑另一种情况,我们将检索与键关联的多个值。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{3, "Hi"}, {3, "Hello"}, {2, "Welcome"}, {3, "Vanakam"}}; auto x = a.equal_range(3); for (auto y = x.first; y != x.second; ++y) { std::cout << "" << y->second << std::endl; } return 0; }

输出

以下是以上代码的输出:

Hi
Hello
Vanakam

示例

在以下示例中,我们将找到键并修改关联的值。

Open Compiler
#include <iostream> #include <map> int main() { std::multimap<int, std::string> a = {{1, "A"}, {2, "B"}, {3, "C"}}; auto x = a.find(1); if (x != a.end()) { x->second = "D"; std::cout << "After Modification Value Is: " << x->second << std::endl; } else { std::cout << "Key Not Found." << std::endl; } return 0; }

输出

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

After Modification Value Is: D
multimap.htm
广告