💡 퀵 접속: cpp.kr/generate
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 모든 요소를 함수를 통해 생성된 값으로 채웁니다. generate는 원본 범위를 직접 수정하며, 각 요소마다 함수를 호출하여 새로운 값을 생성합니다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
int main() {
std::vector<int> numbers(5);
std::cout << "초기 벡터: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// 난수 생성기 설정
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
// 각 요소를 난수로 채움
std::generate(numbers.begin(), numbers.end(),
[&]() { return dis(gen); });
std::cout << "난수로 채운 후: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
초기 벡터: 0 0 0 0 0 난수로 채운 후: 42 17 89 31 65
#include <iostream>
#include <string>
#include <algorithm>
#include <random>
int main() {
std::string text(10, ' ');
std::cout << "초기 문자열: [" << text << "]" << std::endl;
// 난수 생성기 설정
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis('A', 'Z');
// 각 문자를 대문자 난수로 채움
std::generate(text.begin(), text.end(),
[&]() { return static_cast<char>(dis(gen)); });
std::cout << "대문자 난수로 채운 후: [" << text << "]" << std::endl;
return 0;
}
실행 결과:
초기 문자열: [ ] 대문자 난수로 채운 후: [XKQMPRSTUV]
#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(3, Person("", 0));
std::cout << "초기 목록:" << std::endl;
for (const auto& person : people) {
person.print();
}
// 난수 생성기 설정
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> age_dis(20, 50);
// 이름 목록
std::vector<std::string> names = {"Alice", "Bob", "Charlie", "David", "Eve"};
std::uniform_int_distribution<> name_dis(0, names.size() - 1);
// 각 Person 객체를 랜덤한 이름과 나이로 채움
std::generate(people.begin(), people.end(),
[&]() {
return Person(names[name_dis(gen)], age_dis(gen));
});
std::cout << "\n랜덤한 Person 객체로 채운 후:" << std::endl;
for (const auto& person : people) {
person.print();
}
return 0;
}
실행 결과:
초기 목록: (0세) (0세) (0세) 랜덤한 Person 객체로 채운 후: Bob (35세) Eve (42세) Charlie (28세)
| 함수 | 설명 |
|---|---|
| generate(first, last, gen) | [first, last) 범위의 모든 요소를 gen 함수를 호출하여 생성된 값으로 채움 |