Random element in a map

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

    Here is the case when all map items must be access in random order.

    1. Copy the map to a vector.
    2. Shuffle vector.

    In pseudo-code (It closely reflects the following C++ implementation):

    import random
    import time
    
    # populate map by some stuff for testing
    m = dict((i*i, i) for i in range(3))
    # copy map to vector
    v = m.items()
    # seed PRNG   
    #   NOTE: this part is present only to reflect C++
    r = random.Random(time.clock()) 
    # shuffle vector      
    random.shuffle(v, r.random)
    # print randomized map elements
    for e in v:
        print "%s:%s" % e, 
    print
    

    In C++:

    #include 
    #include 
    #include 
    #include 
    
    #include 
    #include 
    #include 
    
    int main()
    {
      using namespace std;
      using namespace boost;
      using namespace boost::posix_time;
    
      // populate map by some stuff for testing
      typedef map Map;
      Map m;
      for (int i = 0; i < 3; ++i)
        m[i * i] = i;
    
      // copy map to vector
    #ifndef OPERATE_ON_KEY
      typedef vector > Vector;
      Vector v(m.begin(), m.end());
    #else
      typedef vector Vector;
      Vector v;
      v.reserve(m.size());
      BOOST_FOREACH( Map::value_type p, m )
        v.push_back(p.first);
    #endif // OPERATE_ON_KEY
    
      // make PRNG
      ptime now(microsec_clock::local_time());
      ptime midnight(now.date());
      time_duration td = now - midnight;
      mt19937 gen(td.ticks()); // seed the generator with raw number of ticks
      random_number_generator rng(gen);
    
      // shuffle vector
      //   rng(n) must return a uniformly distributed integer in the range [0, n)
      random_shuffle(v.begin(), v.end(), rng);
    
      // print randomized map elements
      BOOST_FOREACH( Vector::value_type e, v )
    #ifndef OPERATE_ON_KEY
        cout << e.first << ":" << e.second << " ";
    #else
        cout << e << " ";
    #endif // OPERATE_ON_KEY
      cout << endl;
    }
    

提交回复
热议问题