Pick Random Element From Vector In C++

In this tutorial, we will see how we can pick a random element from the vector in C++. Before moving further we should know what is vector. and how elements are stored, added, and removed elements in that vector. So we can say a vector is like a dynamic array. So with the help of the below example, we will see how we can pick a random element from a vector in C++.

Example 1 – Steps required to pick the random element in vector in C++ –

Step 1 – Add the header file which contains rand() built in function –

#include<iostream>
#include<cstdlib>
#include<vector>

Here cstdlib header file contains rand() function (we can use bits/stdc++.h header file as well) and vector header file contains vector built in functions.

Step 2 –

vector<int>vec1 = {10,11,12,13,14,15,16,17,18,19,20};
    int index = rand()%vec1.size();
    cout<<index<<endl;
    return 0;

In this step, we can get any index value between 0 to 10 using rand() function.

Example 2 – Complete code using rand() function –

#include<iostream>
#include<cstdlib>
#include<vector>
using namespace std;

int main(){
    vector<int>vec1 = {10,11,12,13,14,15,16,17,18,19,20};
    for(int i = 0;i<vec1.size();i++){
        int size = vec1.size();
        int indexx = rand()%size;
        int val = vec1[indexx];
        cout<<"Random element from vector is: "<<val<<" and which is present at index: "<<indexx<<endl;
    }
    return 0;
}

Output – 

Random element from vector is: 18 and which is present at index: 8
Random element from vector is: 19 and which is present at index: 9
Random element from vector is: 19 and which is present at index: 9
Random element from vector is: 11 and which is present at index: 1
Random element from vector is: 17 and which is present at index: 7
Random element from vector is: 15 and which is present at index: 5
Random element from vector is: 15 and which is present at index: 5
Random element from vector is: 20 and which is present at index: 10
Random element from vector is: 11 and which is present at index: 1
Random element from vector is: 10 and which is present at index: 0
Random element from vector is: 17 and which is present at index: 7

In this example, we first create a vector then with the help of rand() built in function we get the random index and then we get the value present at that particular random index. Then we have to print the value and index of that element. This is one of the best and easiest ways to pick the random element from the vector in C++.

Leave a Reply

Your email address will not be published. Required fields are marked *