how to select random element from vector c++ code example

Example 1: select one random element of a vector in c++

vector<int> v{10,21,24,13};

int random = rand() % v.size();
int sel_elem = v[random];

cout<<"Selected Element: "<<sel_elem<<endl;

Example 2: how to get a random element from a vector c++ string

#include <iostream>
#include <vector>
using std::string; 

int main()
{
  std::vector <string> some_vector {"pizza", "burger", "fries", "chicken"}; 
  
  string random = some_vector[rand() % some_vector.size()]; 
  std::cout << random << "\n"; 
 
  
  return 0;
}

Tags:

Cpp Example