C++でstd::vectorをシャッフルする方法
ベクトルシャッフルは、Fisher-Yatesシャッフルアルゴリズムで実行できます。
このアルゴリズムでは、ベクトルの線形スキャンが実行され、各要素が、要素自体を含む残りのすべての要素の中でランダムな要素と交換されます。
アルゴリズム
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.
サンプルコード
#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;
} 出力
Elements after getting shuffled 2 8 5 3 1 9 4 7 6
-
C ++で単一の文字を文字列に変換するにはどうすればよいですか?
単一の文字を文字列に変換する方法はいくつかあります。次の例では、それらの一部を使用して文字を文字列に変換しています。 これは、C++言語で単一の文字を文字列に変換する例です。 例 #include <iostream> #include<string> #include<sstream> int main() { char c = 'm'; std::string s(1, c); std::cout << "Using string c
-
C ++でベクトルの内容を印刷するにはどうすればよいですか?
ベクトルは動的配列に似ていますが、ベクトルのサイズを変更できます。ベクトルは、要素の挿入または削除に応じてサイズを変更できるシーケンスコンテナです。コンテナは、同じタイプのデータを保持するオブジェクトです。 ベクターは、ベクター内の要素の将来の成長のために、追加のストレージを割り当てる場合があります。ベクトル要素は連続したメモリに保存されます。データはベクトルの最後に入力されます。 ベクトルの内容をC++言語で印刷する例を次に示します 例 #include<iostream> #include<vector> void print(std::vector <