How to get a random element from a C++ container?

后端 未结 8 1750
礼貌的吻别
礼貌的吻别 2020-11-27 15:02

What is a good way to get a [pseudo-]random element from an STL range?

The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) an

8条回答
  •  执笔经年
    2020-11-27 15:24

    You can try to get a random number between 0 and the number of elements of the container. You could then access to the corresponding element of the container. For example, you can do this:

    #include 
    #include 
    
    // ...
    std::srand(std::time(0)); // must be called once at the start of the program
    int r = std::rand() % c.size() + 1; 
    container_type::iterator it = c.begin();
    std::advance(it, r);
    

提交回复
热议问题