C++ algorithm random_shuffle() function
Example
Arrange the elements of a vector randomly:
vector<int> numbers = {1, 2, 3, 5, 7, 9};
random_shuffle(numbers.begin(), numbers.end());
for (int number : numbers) {
cout << number << " ";
}
Try it Yourself »
Definition and Usage
The random_shuffle()
function sorts the elements in a data range randomly.
The range of data is specified by iterators.
Note: The example above is likely to always sort the elements in the same way.
In order to change the random sorting you can use the srand()
function to seed the random number generator. To make sure that the order is different every time you can use the current time as a seed as shown below in the More Examples section.
Syntax
random_shuffle(iterator start, iterator end);
Parameter Values
Parameter | Description |
---|---|
start | Required. An iterator pointing to the start of the data range. |
end | Required. An iterator pointing to the end of the data range. Elements up to this position will be included, but the element at this position will not be. |
More Examples
Example
Ensure that the vector is sorted differently each time the program runs:
vector<int> numbers = {1, 2, 3, 5, 7, 9};
srand(time(NULL));
random_shuffle(numbers.begin(), numbers.end());
for (int number : numbers) {
cout << number << " ";
}
Try it Yourself »
Related Pages
Read more about data structures in our Data Structures Tutorial.
Read more about iterators in our Iterators Tutorial.
Read more about algorithms in our Algorithms Tutorial.