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 - 表示要搜尋的鍵。

返回值

如果找到具有特定鍵的元素,則此函式返回指向該元素的迭代器。

示例

讓我們看下面的例子,我們將演示 find() 函式的使用。

#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

示例

考慮另一種情況,我們將檢索與鍵關聯的多個值。

#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

示例

在以下示例中,我們將找到鍵並修改關聯的值。

#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
廣告