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()
?