In the C++ programming language, the Standard Template Library (STL) is a powerful collection of data structures and algorithms. The map is one of the most common associative containers of the STL. A map contains items stored as pairs of keys and values, where keys must be unique and will always be sorted by the provided comparator function.
There are several member functions to efficiently manipulate std::map , one of which is map::end. In C++ , the map end function is used to return an iterator that is next to the last entry in the map. The std::map represents an associative container in the C++ Standard Template Library (STL) that stores elements in sorted order (by default in std::less key order) in key-value pairs.
Syntax:
It has the following syntax:
iterator end(); //until C++ 11
const_iterator end() const; //until C++ 11
iterator end() noexcept; //since C++ 11
const_iterator end() const noexcept; //since C++ 11
In this syntax,
- Parameter: It doesn't have any parameters.
- Return value: It returns an iterator pointing next to the last element of the map.
C++ Simple map::end function Example
Let us take a simple example to illustrate the map::end function in C++.
Example
#include <iostream>
#include <map>
using namespace std; //using standard namespace
int main () //main function
{
map<char,string> mymap;
mymap['b'] = "Java";
mymap['a'] = "C++";
mymap['c'] = "SQL";
// show content:
for (map<char,string>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
cout << it->first << " => " << it->second << '\n';
return 0;
}
Output:
a => C++
b => Java
c => SQL
Explanation:
In this example, we have taken a map<char, string> named mymap that stores key-value pairs where characters are keys and strings are values. After that, the map automatically arranges elements in ascending order of keys.
Features of the map end function in C++
Several features of the map end function in C++ are as follows:
- In C++, each key stored in the map is unique.
- Values are retrievable via the key.
- Internally, the std::map is usually structured as a balanced binary search tree, or (more commonly) a form of a Red-Black tree.
Iterating Over a Map Using for_each and Lambda Function
Let us take an example to illustrate how to iterate over the map using a for-each loop and a lambda expression in C++.
Example
#include <iostream>
#include <map>
#include <string>
#include <iterator>
#include <algorithm>
using namespace std; //using standard namespace
int main() //main function
{
map<string, int> m;
m["Room1"] = 100;
m["Room2"] = 200;
m["Room3"] = 300;
// Create a map iterator and point to the beginning of the map
map<string, int>::iterator it = m.begin();
// Iterate over a map using std::for_each and Lambda function
for_each(m.begin(), m.end(),[](pair<string, int> element){
// Accessing KEY from element
string word = element.first;
// Accessing VALUE from element.
int count = element.second;
cout<<word<<" = "<<count<<endl;
});
return 0;
}
Output:
Room1 = 100
Room2 = 200
Room3 = 300
Explanation:
In this example, we are using an STL algorithm to iterate over the map. It will iterate over each of the map elements and call the callback provided by us.
Traversing a Map Using begin and end Iterators in C++
Let us take a simple example to iterate over the map using a while loop in C++.
Example
#include <iostream>
#include <map>
#include <string>
using namespace std; //using standard namespace
int main() //main function
{
map<int,string> mymap = {
{ 100, "James"},
{ 200, "Jhony" },
{ 300, "Peter" },
{ 400, "Philip" },
{ 500, "Michael" }};
map<int, string>::const_iterator it; // declare an iterator
it = mymap.begin(); // assign it to the start of the vector
while (it != mymap.end()) // while it hasn't reach the end
{
cout << it->first << " = " << it->second << "\n";
// print the value of the element icpp tutorials to
++it; // and iterate to the next element
}
cout << endl;
}
Output:
100 = James
200 = Jhony
300 = Peter
400 = Philip
500 = Michael
Explanation:
In this example, we have created a map<int, string> that stores ID-name pairs. After that, we use a constant iterator (const_iterator) to traverse the map from the begin to end function, which displays each key-value pair sequentially.
Iterating Through a Map and Performing Operations on Key-Value Pairs
Let us take an example to illustrate how to iterate through a map and perform an operation on key-value pairs in C++.
Example
#include <iostream>
#include <string>
#include <map>
using namespace std; //using standard namespace
int main () //main function
{
map<int,int> mymap = {
{ 10, 10},
{ 20, 20 },
{ 30, 30 } };
cout<<"Elements are:" <<endl;
for (map<int,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
cout << it->first
<< " * "
<< it->second
<< " = "
<<it->first * it->second
<< '\n';
return 0;
}
Output:
Elements are:
10 * 10 = 100
20 * 20 = 400
30 * 30 = 900
Explanation
In this example, we have created a map<int, int> as mymap that stores integer key-value pairs. After that, we use an iterator from begin to end that traverses the map and multiplies each key by its corresponding value, which prints the result for every pair.
Conclusion:
In conclusion, the C++ std::map::end is an essential part of working with the std::map container. While it does nocpp tutorial to a specific element, it is important for iteration, comparisons, and safe access patterns inside the container. It provides the logical end of the container, allowing developers to cleanly iterate across elements and determine when operations such as find cannot find the provided key.
C++ map end Function FAQs
1) What happens when we compare iterators from a different map using end in C++?
In C++, comparing iterators (including end) across containers is undefined behavior in C++. As for iterators from different std::map, do not ever compare or mix iterators from distinct map objects, even if they have the same types.
2) Is the end function impacted along with insertions or deletions made in the map?
- Insert: Generally, the end function should be okay, since inserting an element does not invalidate iterators in std::map.
- Delete: Generally, deletions do invalidate iterators to deleted elements. The end function itself generally survives. However, it may be prudent to pull end again if the structure was modified.
3) What value does the map::end function point to in C++?
In C++, the value returned from the map::end function is an iterator pointing one past the last valid element of the map. The value returned is similar to a sentinel value and is mainly used for comparisons in loops and searching.
4) Is the value returned from map::end invalidated after insertion or removal?
In C++, the end iterator will continue to be valid after inserting, but it could be invalidated after the removal of elements, especially adjacent to the last valid element. Lastly, it is good practice to reacquire end after modifying the container.
5) Is the end function the same as the last element in the map?
No, the end function is not the last element because it is an iterator that follows the last element and does not hold any data itself. In order to access the last element, we must step back from the end function, but only if the map is not empty.