Select random element in an unordered_map

前端 未结 5 1081
北海茫月
北海茫月 2021-02-04 05:50

I define an unordered_map like this:

std::unordered_map edges;

Is there a efficient way to choose a rando

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-04 06:21

    The solution of

    std::unordered_map edges;
    auto random_it = std::next(std::begin(edges), rand_between(0, edges.size()));
    

    is extremely slow....

    A much faster solution will be:

    • when assigning edges, simutaneously emplaces its keys to std::vector vec
    • random an int index ranging from 0 to vec.size() - 1
    • then get edges[vec[index]]

提交回复
热议问题