How to select one random element of a vector in C++

1 Answer

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

int main() {

	srand(time(NULL));
	
	std::vector<int> vec{5, 7, 0, 9, 3, 8, 1};
	
	int random_index = rand() % vec.size();
    int n = vec[random_index];

    std::cout << n;
}



/*
run:

9

*/

 



answered Dec 11, 2024 by avibootz
...