
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to shuffle a std::vector in C++
A vector shuffle can be done in the Fisher-Yates shuffle algorithm.
In this algorithm, a linear scan of a vector is done and then swap each element with a random element among all the remaining element, including the element itself.
Algorithm
Begin Declare a function show(). Pass a constructor of a vector as a parameter within show() function. for (auto const& i: input) Print the value of variable i. Declare v of vector type. Initialize some values into v vector in array pattern. Declare a variable size of the integer datatype. Call size() function to get the size of the vector. Initialize size = v.size(). for (int i = 0; i < size - 1; i++) int j = i + rand() % (size - i). call swap() function to swap the values of v[i] and v[j]. print “Elements after getting shuffled”. Call show() function to display the suffled value of v vector. End.
Example Code
#include <iostream> #include <vector> #include <algorithm> using namespace std; void show(vector<int> const &input) { for (auto const& i: input) { std::cout << i << " "; } } int main() { vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int size = v.size(); for (int i = 0; i < size - 1; i++) { int j = i + rand() % (size - i); swap(v[i], v[j]); } cout<<"Elements after getting shuffled"<<endl; show(v); return 0; }
Output
Elements after getting shuffled 2 8 5 3 1 9 4 7 6
- Related Articles
- std::vector::resize() vs. std::vector::reserve() in C++
- Difference between std::vector and std::array in C++
- Java Program to Shuffle Vector Elements
- Removing an element from C++ std::vector by index?
- What is the easiest way to initialize a std::vector with hardcoded elements in C++?
- How to append a vector in a vector in C++?
- Find and print duplicate words in std::vector using STL functions using C++.
- How to convert std::string to LPCSTR in C++?
- How to convert std::string to LPCWSTR in C++?
- How to shuffle a List in Java
- How to concatenate a std::string and an int in C++?
- How to initialize a vector in C++?
- How to convert std::string to lower case in C++?
- How to convert a std::string to const char* or char* in C++?
- How to use std::sort to sort an array in C++

Advertisements