Random element in a map

前端 未结 9 614
面向向阳花
面向向阳花 2021-01-07 16:14

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

9条回答
  •  走了就别回头了
    2021-01-07 16:34

    I like James' answer if the map is small or if you don't need a random value very often. If it is large and you do this often enough to make speed important you might be able to keep a separate vector of key values to select a random value from.

    map<...> MyMap;
    vector<...> MyVecOfKeys; // <-- add keys to this when added to the map.
    
    map<...>::key_type key = MyVecOfKeys[ random_0_to_n(MyVecOfKeys.size()) ];
    map<...>::data_type value = MyMap[ key ];
    

    Of course if the map is really huge you might not be able to store a copy of all the keys like this. If you can afford it though you get the advantage of lookups in logarithmic time.

提交回复
热议问题