Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random element in a map

Tags:

c++

random

map

what is a good way to select a random element from a map? C++. It is my understanding that maps don't have random access iterators. The key is a long long and the map is sparsely populated.

like image 790
Deathbob Avatar asked Oct 01 '08 17:10

Deathbob


People also ask

Is Map random access?

Yes, std::map models AssociativeContainer just as you expect. Are you trying to ask why map is not called a "random access data structure"? That's just because we call it an AssociativeContainer, but the meaning is similar.

How do I get map elements in C++?

C++ map find() function is used to find an element with the given key value k. If it finds the element then it returns an iterator pointing to the element. Otherwise, it returns an iterator pointing to the end of the map, i.e., map::end().

How do you generate a random number in C++?

One way to generate these numbers in C++ is to use the function rand(). Rand is defined as: #include <cstdlib> int rand(); The rand function takes no arguments and returns an integer that is a pseudo-random number between 0 and RAND_MAX.


1 Answers

map<...> MyMap; iterator item = MyMap.begin(); std::advance( item, random_0_to_n(MyMap.size()) ); 
like image 183
James Curran Avatar answered Sep 17 '22 21:09

James Curran