Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

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
...