C++ map cend() Function

Last Updated : 15 May 2026

map cend() Function

In C++, the map::cend() function is used to return a constant iterator pointing to the position next to the last element of the map container. It is commonly used with cbegin() to traverse the map elements in a read-only manner.

Note:-This is a placeholder. No element exists in this location and attempting to access is undefined behavior.

Syntax

It has the following syntax:

Parameters

This function does not contain any parameters.

Return Value

It returns a constant iterator pointing next to the last element of the map.

Examples of map cbegin() Function

Here, we are going to discuss several examples to demonstrate the map cbegin() Function

Example 1: Traverse a Map Using map::cend()

This example demonstrates how to iterate through map elements using the cbegin() and cend() functions in C++.

Output:

mymap contains: [a:200] [b:100] [c:300]

In the above example, cend() function is used to return an iterator pointing next to the last element in the mymap map.

Example 2: Iterate Over a Map Using for_each() and map::cend()

This example demonstrates how to traverse all elements of a map using the for_each() algorithm along with the cend() function.

Output:

Room1 = 100
Room2 = 200
Room3 = 300 

In the above example, we are using an STL algorithm std::for-each to iterate over the map. It will iterate on each of the map element and call the callback provided by us.

Example 3: Traverse a Map Using a While Loop and map::cend()

This example demonstrates how to use a while loop with a constant iterator and the cend() function to access map elements.

Output:

100 = Nikita
200 = Deep
300 = Priya
400 = Suman
500 = Aman

In the above example, cend() function is used to return a constant iterator pointing next to the last element in the mymap map.

: Example 4: Demonstrate the Position Returned by map::cend()

This example demonstrates how the cend() function points to the position next to the last element of the map container.

Output:

Elements are:
10 + 10 = 20
20 + 20 = 40
30 + 30 = 60
end element (point next to the last): {3, 0}

In the above example, cend() function is used to return a constant iterator pointing next to the last element in the mymap map.

Next TopicC++ Map