Random element in a map

前端 未结 9 624
面向向阳花
面向向阳花 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:49

    Continuing ryan_s theme of preconstructed maps and fast random lookup: instead of vector we can use a parallel map of iterators, which should speed up random lookup a bit.

    map const original;
    ...
    
    // construct index-keyed lookup map   
    map::const_iterator> fast_random_lookup;
    map::const_iterator it = original.begin(), itEnd = original.end();
    for (unsigned i = 0; it != itEnd; ++it, ++i) {
      fast_random_lookup[i] = it;
    }
    
    // lookup random value
    V v = *fast_random_lookup[random_0_to_n(original.size())];
    

提交回复
热议问题