💡 퀵 접속: cpp.kr/shuffle
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 요소들을 무작위로 섞습니다. shuffle은 원본 범위를 직접 수정하며, 주어진 난수 생성기를 사용하여 요소들의 위치를 무작위로 재배치합니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "원본 벡터: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// 난수 생성기 초기화
std::random_device rd;
std::mt19937 gen(rd());
// 벡터 섞기
std::shuffle(numbers.begin(), numbers.end(), gen);
std::cout << "섞은 후: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
원본 벡터: 1 2 3 4 5 6 7 8 9 10 섞은 후: 7 2 9 1 5 8 3 10 4 6
#include <iostream>
#include <string>
#include <algorithm>
#include <random>
int main() {
std::string str = "Hello, World!";
std::cout << "원본 문자열: " << str << std::endl;
// 난수 생성기 초기화
std::random_device rd;
std::mt19937 gen(rd());
// 문자열 섞기
std::shuffle(str.begin(), str.end(), gen);
std::cout << "섞은 후: " << str << std::endl;
return 0;
}
실행 결과:
원본 문자열: Hello, World! 섞은 후: lW!o,dlHlre o
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <random>
class Person {
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
void print() const {
std::cout << name << " (" << age << "세)" << std::endl;
}
};
int main() {
std::vector<Person> people = {
Person("Alice", 20),
Person("Bob", 30),
Person("Charlie", 25),
Person("David", 35),
Person("Eve", 22)
};
std::cout << "원본 리스트:" << std::endl;
for (const auto& person : people) {
person.print();
}
// 난수 생성기 초기화
std::random_device rd;
std::mt19937 gen(rd());
// 리스트 섞기
std::shuffle(people.begin(), people.end(), gen);
std::cout << "\n섞은 후:" << std::endl;
for (const auto& person : people) {
person.print();
}
return 0;
}
실행 결과:
원본 리스트: Alice (20세) Bob (30세) Charlie (25세) David (35세) Eve (22세) 섞은 후: David (35세) Alice (20세) Eve (22세) Charlie (25세) Bob (30세)
| 함수 | 설명 |
|---|---|
| shuffle(first, last, g) | 범위 [first, last)의 요소들을 난수 생성기 g를 사용하여 무작위로 섞음 |