How to Use C++ random_shuffle()

The random_shuffle() function is used to randomly rearrange elements within a specified range.

Function definition:

template <class RandomAccessIterator>
void random_shuffle(RandomAccessIterator first, RandomAccessIterator last);

Explanation of parameters:

  1. RandomAccessIterator: the starting iterator of the range of elements to be rearranged.
  2. first: the starting position of the range of elements to be rearranged.
  3. last: The ending position of the range of elements to be reordered, excluding the element at that position.

Example of use:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    
    // 重排整个向量
    std::random_shuffle(vec.begin(), vec.end());
    
    // 输出重排后的结果
    for (auto num : vec) {
        std::cout << num << " ";
    }
    
    return 0;
}

Output result:

4 3 1 2 5

The random_shuffle() function will randomly rearrange the elements within a specified range. The result of the rearrangement may vary each time it is run. In the example above, the output is the result of randomly shuffling the original vector {1, 2, 3, 4, 5}.

It is important to note that the random_shuffle() function is only suitable for random access iterators, such as vectors and arrays. For other types of containers, you can use the shuffle() function for similar operations.

bannerAds