How to get random element from a vector in C++

3 Answers

0 votes
#include <iostream>
#include <vector>

int random_between_range(int first, int last) {
    int number = rand()%((last + 1) - first) + first;

    return number;
}
  
int main()
{
    srand(time(NULL));
    
    std::vector<int> vec = { 5, 2, 7, 1, 9, 3, 6, 4 };
     
    int index = random_between_range(0, vec.size());
     
    std::cout << vec[index];
}
 
   
   
   
/*
run:
   
1
    
*/

 

 



answered Dec 7, 2022 by avibootz
0 votes
#include <iostream>
#include <vector>

int main()
{
    srand(time(NULL));
    
    std::vector<int> vec = { 5, 2, 7, 1, 9, 3, 6, 4 };

    std::cout << vec[rand() % vec.size()];
}
 
   
   
   
/*
run:
   
9
    
*/

 

 



answered Dec 7, 2022 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <random>

int main()
{
    std::vector<int> vec = { 5, 2, 7, 1, 9, 3, 6, 4, 0 };

    std::mt19937 generator(std::random_device{}());

    std::uniform_int_distribution<std::size_t> distribution(0, vec.size() - 1);

    std::size_t index = distribution(generator);
    
    std::cout << vec[index];
}




/*
run:

1

*/

 



answered Jan 6, 2023 by avibootz
...