How to Shuffle a Vector in C++?
Last Updated :
02 Feb, 2024
Shuffling a vector means rearranging the position of its elements in random order. In this article, we will look at how to shuffle the vector in C++.
Example
Input:
myVector = {1, 2, 3, 4, 5, 6, 7}
Output:
myVector = {1, 3, 7, 6, 4, 2, 5}
Shuffle a Vector in C++
In C++, the STL in C++ provides a std::shuffle() function that conveniently shuffles the elements of a vector. It is defined inside <algorithm> header files and requires the vector and a random number generation to work.
C++ Program to Shuffle a Vector in C++
C++
#include <algorithm>
#include <iostream>
#include <random>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5, 6, 7 };
random_device rd;
mt19937 g(rd());
shuffle(vec.begin(), vec.end(), g);
cout << "Shuffled vector: " ;
for ( int num : vec) {
cout << num << " " ;
}
cout << endl;
return 0;
}
|
Output
Shuffled vector: 2 1 4 5 3 7 6
Share your thoughts in the comments
Please Login to comment...