💡 퀵 접속: cpp.kr/fill

fill

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위의 모든 요소를 특정 값으로 채웁니다. fill은 원본 범위를 직접 수정하며, 범위 내의 모든 요소를 동일한 값으로 설정합니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers(5);
    
    std::cout << "초기 벡터: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    // 모든 요소를 42로 채움
    std::fill(numbers.begin(), numbers.end(), 42);
    
    std::cout << "42로 채운 후: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

초기 벡터: 0 0 0 0 0
42로 채운 후: 42 42 42 42 42

문자열에서 사용

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string text(10, ' ');
    
    std::cout << "초기 문자열: [" << text << "]" << std::endl;
    
    // 모든 문자를 '*'로 채움
    std::fill(text.begin(), text.end(), '*');
    
    std::cout << "'*'로 채운 후: [" << text << "]" << std::endl;
    
    return 0;
}

실행 결과:

초기 문자열: [          ]
'*'로 채운 후: [**********]

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

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();
    }
    
    // 모든 요소를 기본 Person 객체로 채움
    std::fill(people.begin(), people.end(), Person("Unknown", 0));
    
    std::cout << "\n기본 Person 객체로 채운 후:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    return 0;
}

실행 결과:

초기 목록:
 (0세)
 (0세)
 (0세)

기본 Person 객체로 채운 후:
Unknown (0세)
Unknown (0세)
Unknown (0세)

참고사항

  • fill은 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위를 직접 수정합니다.
  • 시간 복잡도는 O(n)입니다.
  • 범위 내의 모든 요소가 동일한 값으로 설정됩니다.
  • 요소의 순서는 유지됩니다.
  • 예외 안전성을 보장합니다.
  • fill_n은 지정된 개수만큼 요소를 채우는 버전입니다.
  • generate는 각 요소를 함수로 생성하는 버전입니다.
함수 설명
fill(first, last, value) [first, last) 범위의 모든 요소를 value로 채움