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

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

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

+6
source share
4 answers

There is no "last element" in the container that is unordered .

You may need an ordered container, for example. std::map and access the last element using mymap.rbegin()->first (Also see this post )

EDIT:

To check if your iterator is near the end, just increase it (and maybe keep it in a temporary order) and check it at mymap.end() or even a cleaner one: if (std::next(it) == last)

+8
source

You can not. by definition, an element is not stored based on some order. the key is hashed first, and why O (1) lookup is possible. if you want to check if the key exists in unordered_map or not, you can use this code:

 std::unordered_map dico; if(dico.count(key)!=0){ //code here } 
+1
source
 std::unordered_map::iterator last_elem; for (std::unordered_map::iterator iter = myMap.begin(); iter != myMap.end(); iter++) last_elem = iter; // use last_elem, which now points to the last element in the map 

This will give you the last item in any order that the map gives you.

Edit: You need to use std::unordered_map<YourKeyType, YourValueType> instead of std::unordered_map . I just wrote it like this because you did not specify the type in your question.

Alternatively, as suggested by vsoftco (thanks), you can declare both last_elem and iter as decltype(myMap)::iterator .

(If you are compiling the MSVC ++ compiler, you need to add typedef decltype(myMap) map_type; and then use map_type::iterator instead of decltype(myMap)::iterator map_type::iterator .)

+1
source

In your comments, it seems your goal is to determine if you are in the last element when iterating forward. This is much easier 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 with any iterable range (including arrays, std containers, or custom containers).

We check if we are end (in this case we are not the last element, and promotion will be illegal).

If we are not end , we see that std::next us end . If so, we are the last element.

Otherwise, we do not.

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

0
source

Source: https://habr.com/ru/post/973439/


All Articles