Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last element of an std::unordered_map?

Tags:

c++

How to get the last element of an std::unordered_map?

myMap.rbegin() and --myMap.end() are not possible.

like image 830
Korchkidu Avatar asked Aug 06 '14 16:08

Korchkidu


1 Answers

In your comments, it appears your goal is to determine if you are on the last element when iterating forward. This is a far easier problem to solve than finding the last element:

template<class Range, class Iterator>
bool is_last_element_of( Range const& r, Iterator&& it ) {
  using std::end;
  if (it == end(r)) return false;
  if (std::next(std::forward<Iterator>(it)) == end(r)) return true;
  return false;
}

the above should work on any iterable Range (including arrays, std containers, or custom containers).

We check if we are end (in which case, we aren't the last element, and advancing would be illegal).

If we aren't end, we see if std::next of us is end. If so, we are the last element.

Otherwise, we are not.

This will not work on iterators that do not support multiple passes.

like image 106
Yakk - Adam Nevraumont Avatar answered Oct 15 '22 15:10

Yakk - Adam Nevraumont