Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if iterator is last element of std::map

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

like image 978
DJMcMayhem Avatar asked Nov 11 '15 18:11

DJMcMayhem


People also ask

How do I find the last element of my iterator?

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.

How do you find the last element on a map?

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.

How do you check if an element in a map exists?

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 ...

Does map return an iterator?

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.


Video Answer


1 Answers

Use std::next from <iterator> as

if (std::next(iter) == charMap.end())
    std::cout << "\t//This is the last element.\n";

instead.

like image 129
vsoftco Avatar answered Sep 25 '22 19:09

vsoftco