Random element in a map

前端 未结 9 616
面向向阳花
面向向阳花 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<K, V> const original;
    ...
    
    // construct index-keyed lookup map   
    map<unsigned, map<K, V>::const_iterator> fast_random_lookup;
    map<K, V>::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())];
    
    0 讨论(0)
  • 2021-01-07 16:50

    Has anyone tried this? https://github.com/mabdelazim/Random-Access-Map "C++ template class for random access map. This is like the std::map but you can access items random by index with syntax my_map.key(i) and my_map.data(i)"

    0 讨论(0)
  • 2021-01-07 16:55

    If your map is static, then instead of a map, use a vector to store your key/value pairs in key order, binary search to look up values in log(n) time, and the vector index to get random pairs in constant time. You can wrap the vector/binary search to look like a map with a random access feature.

    0 讨论(0)
提交回复
热议问题