C++ Algorithm Generate: std::fill, std::generate & std::iota Guide

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

AlgorithmHeaderRoleTime
fill<algorithm>Single valueO(N)
fill_n<algorithm>First n with one valueO(N)
generate<algorithm>Callable per elementO(N)
generate_n<algorithm>n elements from callableO(N)
iota<numeric>Sequential valuesO(N)

6. Common pitfalls

  • Zero size: fill/generate on empty range does nothing — resize first or use generate_n + back_inserter.
  • Capture: use [&counter] not [=] when the lambda must update outer state.
  • Random: use C++11 <random>, not rand().
  • Performance: fill is often faster than generate returning a constant; use fill for constants.

7. Test data generator

The TestDataGenerator example (random, sequence, constant, pattern, custom) is unchanged from the source article.


Summary

  1. fill — one value, fast
  2. fill_n — first n with one value
  3. generate / generate_n — flexible generation
  4. iota — sequential values in <numeric>

Next steps

  • C++ Algorithm Reverse
  • C++ Algorithm Count

  • C++ Algorithm Copy

Keywords

std::fill, std::generate, std::iota, fill_n, generate_n, STL, C++