function template
<algorithm>

std::shuffle

template <class RandomAccessIterator, class URNG>  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g);
使用生成器隨機重排範圍內的元素
使用g作為均勻隨機數生成器,隨機重排範圍[first,last)內的元素。

該函式透過呼叫g()來確定所選的元素,並將每個元素的值與某個其他隨機選擇的元素的值進行交換。

此函式適用於標準生成器,如<random>中定義的生成器。要不使用此類生成器對範圍內的元素進行隨機重排,請參見random_shuffle

此函式模板的行為等同於
1
2
3
4
5
6
7
8
template <class RandomAccessIterator, class URNG>
  void shuffle (RandomAccessIterator first, RandomAccessIterator last, URNG&& g)
{
  for (auto i=(last-first)-1; i>0; --i) {
    std::uniform_int_distribution<decltype(i)> d(0,i);
    swap (first[i], first[d(g)]);
  }
}

引數

first, last
Forward iterators 指向要隨機重排的序列的初始和結束位置。使用的範圍是[first,last),它包含first指向的元素以及它和last指向元素之間的所有元素,但不包含last指向的元素。
ForwardIterator 應指向一個已定義swap 並且能夠交換其引數值的型別。
g
用作隨機性來源的均勻隨機數生成器。
URNG 應為均勻隨機數生成器,例如標準生成器類之一(有關更多資訊,請參閱<random>)。

返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// shuffle algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::shuffle
#include <array>        // std::array
#include <random>       // std::default_random_engine
#include <chrono>       // std::chrono::system_clock

int main () {
  std::array<int,5> foo {1,2,3,4,5};

  // obtain a time-based seed:
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();

  shuffle (foo.begin(), foo.end(), std::default_random_engine(seed));

  std::cout << "shuffled elements:";
  for (int& x: foo) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

可能的輸出
shuffled elements: 3 1 4 2 5


複雜度

firstlast之間距離減一成線性關係:獲取隨機值並交換元素。

資料競爭

範圍[first,last)內的物件將被修改。

異常

如果任何隨機數生成、元素交換或迭代器操作引發異常,則會丟擲異常。
請注意,無效引數會導致未定義行為

另見