0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C++ vectorの要素をシャッフルする

Last updated at Posted at 2022-04-23

はじめに

vectorの要素をシャッフルにはstd::shuffleという標準ライブラリがあります。
基本的にはこちらを使いましょう。

ですが、自分でロジックを組んでみたかったので、
引数にいれたvector(ここではint型)の要素をシャッフルする関数をつくりました。
中身のデータがランダムに並べ替えられます。

シャッフルの処理ロジックってどんなのだろうってなった方のご参考になれれば幸いです。

関数

void shuffle(std::vector<int> *list)
{
	for (std::vector<int>::reverse_iterator itr = (*list).rbegin(); itr != (*list).rend(); ++itr)		// ①
	{
		int r = rand() % (*list).size();		// ②
		int temp = (*itr);		// ③
		(*itr) = (*list).at(r);		// ④
		(*list).at(r) = temp;		// ⑤
	}
}

ざっくり説明

vectorの要素をほかの1要素と入れ替える、という処理をvectorの後ろのデータから順に行います。

  • reverse_iteratorで並びかえるデータを後ろから順に走査します。①
  • 要素の1つをランダムに選びます。②
  • いまのforループで走査しているデータを一時保存します。③
  • いまのforループで走査しているデータを、ランダムで選んだ要素のデータに上書きします。④
  • ランダムで選んだ要素のデータを、いまのforループで走査しているデータに上書きします。⑤

※ランダムに選ぶところrand()を使っているので、あんまりランダムじゃないです。この点でもstd::shuffleの方が良いです。

使用例

std::vector<int> data = {0, 1, 2, 3, 4};

shuffle(&data);

0
0
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?