Select random element in an unordered_map

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

    This is how you can get random element from a map:

    std::unordered_map edges;
    iterator item = edges.begin();
    int random_index = rand() % edges.size();
    std::advance(item, random_index);
    

    Or take a look at this answer, which provides the following solution:

    std::unordered_map edges;
    iterator item = edges.begin();
    std::advance( item, random_0_to_n(edges.size()) );
    

提交回复
热议问题