C++ multimap::find() Function



The C++ std::multimap::find() function searches for a specific key within the multimap. It returns an iterator pointing to the first occurrence of the key, or end() if not found. Unlike map, multimap allows duplicate keys. It is commonly used to retrieve elements associated with a particular key, enabling easy access to all values mapped to that key. The time complexity of this function is logarithmic i.e.O(log n ).

Syntax

Following is the syntax for std::multimap::find() function.

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

Parameters

  • k − It indicates the key to be searched.

Return value

This function returns an iterator to the element, if an element with specific key is found.

Example

Let's look at the following example, where we are going to demonstrate the usage of find() function.

#include 
#include 
int main()
{
    std::multimap 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;
}

Output

Output of the above code is as follows −

Key Found : A

Example

Consider the another scenario, where we are going to retrieve the multiple values associated with the key.

#include 
#include 
int main()
{
    std::multimap 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;
}

Output

Following is the output of the above code −

Hi
Hello
Vanakam

Example

In the following example, we are going to find the key and modifying the associated value.

#include 
#include 
int main()
{
    std::multimap 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;
}

Output

If we run the above code it will generate the following output −

After Modification Value Is: D
multimap.htm
Advertisements