This is similar to this question , but not a duplicate. I am trying to iterate over a map and print out the values โโof each element, but with a slightly different output on the last element. In this question, they recommend using map.rbegin().base() , but it does not work 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 expect my output to look like this:
a: 1 b: 2 c: 3 d: 4
But instead, I get this output:
a: 1 b: 2 c: 3 d: 4
Now I understand that there is a better way to do this, but I expect this to work too. Why can't I compare iter and charMap.rbegin().base() ?
source share