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++
// C++ Program to Shuffle Elements in a Vector #include <algorithm> #include <iostream> #include <random> #include <vector> using namespace std;
int main()
{ // Create a vector of elements
vector< int > vec = { 1, 2, 3, 4, 5, 6, 7 };
// Initialize random number generator
random_device rd;
mt19937 g(rd());
// Shuffle the vector
shuffle(vec.begin(), vec.end(), g);
// Display the shuffled vector
cout << "Shuffled vector: " ;
for ( int num : vec) {
cout << num << " " ;
}
cout << endl;
return 0;
} |
Output
Shuffled vector: 2 1 4 5 3 7 6