Select random element in an unordered_map

前端 未结 5 1078
北海茫月
北海茫月 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:35

    Pre-C++11 solution:

    std::tr1::unordered_map edges;
    std::tr1::unordered_map::iterator random_it = edges.begin();
    std::advance(random_it, rand_between(0, edges.size()));
    

    C++11 onward solution:

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

    The function that selects a valid random number is up to your choice, but be sure it returns a number in range [0 ; edges.size() - 1] when edges is not empty.

    The std::next function simply wraps the std::advance function in a way that permits direct assignation.

提交回复
热议问题