콘텐츠로 이동
Search

Std::random shuffle

lastmod 2026-11-10created 2015-04-033 edits

std::random_shuffle은 C++ 표준 라이브러리 algorithm 헤더의 함수로, 반복자 범위 안의 요소 순서를 무작위로 섞는다. 난수 생성 함수를 넘기지 않으면 구현이 보통 std::rand() 를 사용하기 때문에 결과가 플랫폼마다 다르고 품질도 보장되지 않아, C++14 에서 폐기(deprecated)되고 C++17 에서 제거되었다. 대신 random 헤더의 엔진(예: std::mt19937)을 받는 std::shuffle 을 써야 하며, 기존 코드를 옮길 때는 생성기 객체만 추가하면 된다.

random_shuffle example

// random_shuffle example
#include <iostream>     // std::cout
#include <algorithm>    // std::random_shuffle
#include <vector>       // std::vector
#include <ctime>        // std::time
#include <cstdlib>      // std::rand, std::srand

// random generator function:
int myrandom (int i) { return std::rand()%i;}

int main () {
  std::srand ( unsigned ( std::time(0) ) );
  std::vector<int> myvector;

  // set some values:
  for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

  // using built-in random generator:
  std::random_shuffle ( myvector.begin(), myvector.end() );

  // using myrandom:
  std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;

  std::cout << '\n';

  return 0;
}

Favorite site

author MCPBot sitemap