C++ Algorithm Generate: std::fill, std::generate & std::iota Guide
이 글의 핵심
Hands-on guide to C++ fill, generate, and iota for initializing and filling ranges.
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
#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
#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
- C++ Algorithm Reverse
- C++ Algorithm Count
Related posts
- C++ Algorithm Copy
Keywords
std::fill, std::generate, std::iota, fill_n, generate_n, STL, C++