GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::ranges::shuffle - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. algorithm
  3. shuffle

最終更新日時: 2026年09月19日 21時31分51秒 (JST)
rotarymars が更新

履歴 編集

function template
<algorithm>

std::ranges::shuffle(C++20)

namespace std::ranges {
  template <random_access_iterator I,
            sentinel_for<I> S,
            class Gen>
    requires permutable<I> &&
             uniform_random_bit_generator<remove_reference_t<Gen>>
  I
    shuffle(I first,
            S last,
            Gen&& g); // (1) C++20

  template <random_access_range R,
            class Gen>
    requires permutable<iterator_t<R>> &&
             uniform_random_bit_generator<remove_reference_t<Gen>>
  borrowed_iterator_t<R>
    shuffle(R&& r,
            Gen&& g); // (2) C++20
}

概要

範囲のそれぞれの要素を同じ確率で並び替える。

  • (1): イテレータ範囲を指定する
  • (2): Rangeを直接指定する

計算量

正確に (last - first) - 1 回 swap する。

備考

以下の実装では、フィッシャー - イェーツのシャッフルアルゴリズムが使用されている:

  • GCC: 4.9 (libstdc++)
  • Clang: 3.4 (libc++)
  • Visual C++: 2013

例

整数の配列をシャッフルする

#include <algorithm>
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
#include <random>
#include <cstdint>

int main() {
  std::vector<int> v(10);
  std::iota(v.begin(), v.end(), 0); // 0~9 までの値を生成

  std::cout << "before: ";
  std::ranges::copy(v, std::ostream_iterator<int>(std::cout));
  std::cout << std::endl;

  // シャッフル
  std::random_device seed_gen;
  std::uint32_t seed = seed_gen();
  std::mt19937 engine(seed);
  std::ranges::shuffle(v, engine);

  std::cout << " after: ";
  std::ranges::copy(v, std::ostream_iterator<int>(std::cout));
  std::cout << std::endl;
}

出力例

before: 0123456789
 after: 5803429716

文字列をシャッフルする

#include <algorithm>
#include <iostream>
#include <string>
#include <random>
#include <cstdint>

int main() {
  std::string input = "0123456789abcdef";

  std::cout << "before: " << input << std::endl;

  // シャッフル
  std::random_device seed_gen;
  std::uint32_t seed = seed_gen();
  std::mt19937 engine(seed);
  std::ranges::shuffle(input, engine);

  std::cout << " after: " << input << std::endl;
}

出力例

before: 0123456789abcdef
 after: 49e351b8f0ad62c7

バージョン

言語

  • C++20

処理系

  • Clang: 16.0.6 ✅
  • GCC: 10.1.0 ✅
  • Visual C++: 2019 Update 10 ✅

参照

  • N4861 25 Algorithms library
  • LWG Issue 3191. std::ranges::shuffle synopsis does not match algorithm definition
    • C++20で、シノプシスとアルゴリズム定義の不一致を解消するため、冗長なconvertible_to制約がシノプシスから削除された
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.