C++ multimap::cbegin() Function



The C++ std::multimap::cbegin() function is used to return a constant iterator to the first element in the multimap, enabling read-only access to its elements. Unlike begin() function, which returns a mutable iterator, cbegin() function ensures that the data cannot be modified, increasing safe iteration over its elements. The time complexity of this function is constant i.e.O(1).

Syntax

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

const_iterator cbegin() const noexcept;

Parameters

This function does not accepts any parameter.

Return value

This function returns a constant iterator pointing to the first element.

Example

Let's look at the following example, where we are going to use the cbegin() function and accessing the first element.

#include 
#include 
int main()
{
    std::multimap a = {{1, "Welcome"}, {2, "Hi"}, {3, "Hello"}};
    auto it = a.cbegin();
    std::cout << " " << it->first << ": " << it->second << std::endl;
    return 0;
}

Output

Output of the above code is as follows −

1: Welcome

Example

Consider the following example, where we are going to find the specific element using cbegin() function.

#include 
#include 
int main()
{
    std::multimap a = {{1, "Hi"}, {2, "Hello"}, {3, "Namaste"}};
    auto x = a.cbegin();
    while (x != a.cend() && x->first != 3) {
        ++x;
    }
    if (x != a.cend()) {
        std::cout << "Element found: " << x->second << std::endl;
    } else {
        std::cout << "Element not found." << std::endl;
    }
    return 0;
}

Output

Following is the output of the above code −

Element found: Namaste

Example

In the following example, we are going to iterate through the multimap using the cbegin() function.

#include 
#include 
int main()
{
    std::multimap a = {{1, "TutorialsPoint"}, {2, "TP"}, {3, "Tutorix"}};
    for(auto x = a.cbegin(); x != a.cend(); ++x) {
        std::cout << x->first << ": " << x->second << std::endl;
    }
    return 0;
}

Output

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

1: TutorialsPoint
2: TP
3: Tutorix
multimap.htm
Advertisements