Computer >> Máy Tính >  >> Lập trình >> C ++

Cách xáo trộn một std ::vector trong C ++

Xáo trộn vectơ có thể được thực hiện trong thuật toán xáo trộn Fisher-Yates.

Trong thuật toán này, quét tuyến tính một vectơ được thực hiện và sau đó hoán đổi từng phần tử với một phần tử ngẫu nhiên trong số tất cả các phần tử còn lại, bao gồm cả chính phần tử đó.

Thuật toán

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.

Mã mẫu

#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;
}

Đầu ra

Elements after getting shuffled
2 8 5 3 1 9 4 7 6