使用 C++ STL 打亂陣列


在這裡我們將看到 C++ 中的 shuffle 和 random_shuffle。這些函式用於打亂 C++ 中的陣列元素。我們也可以使用向量而不是陣列,用法類似。讓我們先看看 random_shuffle()。它用於隨機重新排列範圍 [left, right) 內的元素。此函式隨機交換每個元素與其一些隨機選擇的其他元素的位置。

我們可以提供一些隨機生成器函式來指定每次選擇哪個元素。如果我們不提供,它將使用它自己的隨機生成器函式。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int myRandomGenerator(int j) {
   return rand() % j;
}
main() {
   srand(unsigned(time(0)));
   vector<int> arr;
   for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
   arr.push_back(j);
   random_shuffle(arr.begin(), arr.end()); //use inbuilt random function to shuffle
   cout << "arr elements:";
   for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
   cout << ' ' << *i;
   cout << endl;
   // using myRandomGenerator
   random_shuffle(arr.begin(), arr.end(), myRandomGenerator);
   cout << "arr elements:";
   for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
   cout << ' ' << *i;
   cout << endl;
}

輸出

arr elements: 5 14 15 6 3 16 13 12 10 2 4 1 17 9 18 11 7 8 19
arr elements: 8 10 5 6 14 1 15 3 19 16 13 18 7 9 4 12 11 17 2

現在讓我們看看 shuffle() 函式是什麼。它也用於隨機重新排列範圍 [left, right) 內的元素。它需要一個均勻隨機數生成器。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
main() {
   vector<int> arr;
   unsigned seed = 0;
   for (int j = 1; j < 20; ++j) //generate 20 numbers and add them into vector arr
   arr.push_back(j);
   shuffle(arr.begin(), arr.end(), default_random_engine(seed));
   cout << "arr elements:";
   for (vector<int>::iterator i = arr.begin(); i != arr.end(); ++i)
   cout << ' ' << *i;
   cout << endl;
}

輸出

arr elements: 19 7 5 6 12 4 13 3 1 17 11 14 18 2 8 15 9 10 16

random_shuffle() 和 shuffle() 之間的唯一區別在於,random_shuffle() 使用 rand() 函式生成隨機索引,而 shuffle() 使用均勻隨機數生成器。但是,如果我們使用均勻隨機數生成器傳遞給 random_shuffle(),則它將生成某種結果。

更新於:2019-12-30

647 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.