[2026] C++ Algorithm Generate: std::fill, std::generate & std::iota Complete Guide
이 글의 핵심
Fill ranges with std::fill and fill_n, generate values with std::generate and generate_n, and build sequences with std::iota from numeric.h — lambdas, functors, and pitfalls.
Introduction
STL generation algorithms fill containers or produce values from a generator: fill, generate, iota, and related helpers keep initialization code short and clear.
1. std::fill
Basic use
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(10);
std::fill(v.begin(), v.end(), 42);
for (int x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
std::fill_n
다음은 cpp를 활용한 상세한 구현 코드입니다. 필요한 모듈을 import하고, 반복문으로 데이터를 처리합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> v(10, 0);
std::fill_n(v.begin(), 5, 1);
for (int x : v) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
2. std::generate / generate_n
Use a generator callable; generate_n with back_inserter appends n generated values.
3. std::iota
Fills [first, last) starting from value, using ++ for each successive element. Include <numeric>.
4. Practical examples
Examples in the Korean article cover random numbers (<random>), functor counters, struct initialization, and ID generators — same code; prefer <random> over rand().
5. Comparison
| Algorithm | Header | Role | Time |
|---|---|---|---|
fill | <algorithm> | Single value | O(N) |
fill_n | <algorithm> | First n with one value | O(N) |
generate | <algorithm> | Callable per element | O(N) |
generate_n | <algorithm> | n elements from callable | O(N) |
iota | <numeric> | Sequential values | O(N) |
6. Common pitfalls
- Zero size:
fill/generateon empty range does nothing —resizefirst or usegenerate_n+back_inserter. - Capture: use
[&counter]not[=]when the lambda must update outer state. - Random: use C++11
<random>, notrand(). - Performance:
fillis often faster thangeneratereturning a constant; usefillfor constants.
7. Test data generator
The TestDataGenerator example (random, sequence, constant, pattern, custom) is unchanged from the source article.
Summary
- fill — one value, fast
- fill_n — first n with one value
- generate / generate_n — flexible generation
- iota — sequential values in
<numeric>
Next steps
Related posts
Keywords
std::fill, std::generate, std::iota, fill_n, generate_n, STL, C++