This is similar to this question but not a duplicate. I'm trying to iterate through a map and print the values of each element, but with slightly different output on the last element. In that question, they recommend using map.rbegin().base()
, but it's not working for me.
Here is my code:
#include <iostream>
#include <map>
int main()
{
std::map <char, int> charMap = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4} };
for (auto iter = charMap.begin(); iter != charMap.end(); iter++)
{
std::cout << iter->first << ":\t" << iter->second;
if (iter == charMap.rbegin().base())
std::cout << "\t//This is the last element.\n";
else
std::cout << "\n";
}
}
I'd expect my output to look like this:
a: 1
b: 2
c: 3
d: 4 //This is the last element.
But instead, I am getting this output:
a: 1
b: 2
c: 3
d: 4
Now I realize that there is a better way to do this, but I would expect this to work also. Why can't I compare iter
and charMap.rbegin().base()
?
To get the last element in an iterator loop you can use std::next() (from C++11). The loop is generally terminated by iterator != container. end() , where end() returns an iterator that points to the past-the-end element.
The C++ function std::map::end() returns an iterator which points to past-the-end element in the map. The past-the-end element is the theoretical element that would follow the last element in the map.
To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...
map() loops over the items of an input iterable (or iterables) and returns an iterator that results from applying a transformation function to every item in the original input iterable.
Use std::next
from <iterator>
as
if (std::next(iter) == charMap.end())
std::cout << "\t//This is the last element.\n";
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With