💡 퀵 접속: cpp.kr/fill_n
C++ 표준 라이브러리의 알고리즘으로, 주어진 위치부터 시작하여 지정된 개수만큼의 요소를 특정 값으로 채웁니다. fill_n은 원본 범위를 직접 수정하며, 지정된 개수만큼의 연속된 요소를 동일한 값으로 설정합니다.
#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;
// 처음 3개의 요소를 42로 채움
std::fill_n(numbers.begin(), 3, 42);
std::cout << "처음 3개를 42로 채운 후: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
초기 벡터: 0 0 0 0 0 처음 3개를 42로 채운 후: 42 42 42 0 0
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text(10, ' ');
std::cout << "초기 문자열: [" << text << "]" << std::endl;
// 처음 5개의 문자를 '*'로 채움
std::fill_n(text.begin(), 5, '*');
std::cout << "처음 5개를 '*'로 채운 후: [" << text << "]" << std::endl;
return 0;
}
실행 결과:
초기 문자열: [ ] 처음 5개를 '*'로 채운 후: [***** ]
#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(5, Person("", 0));
std::cout << "초기 목록:" << std::endl;
for (const auto& person : people) {
person.print();
}
// 처음 3개의 요소를 기본 Person 객체로 채움
std::fill_n(people.begin(), 3, Person("Unknown", 0));
std::cout << "\n처음 3개를 기본 Person 객체로 채운 후:" << std::endl;
for (const auto& person : people) {
person.print();
}
return 0;
}
실행 결과:
초기 목록: (0세) (0세) (0세) (0세) (0세) 처음 3개를 기본 Person 객체로 채운 후: Unknown (0세) Unknown (0세) Unknown (0세) (0세) (0세)
| 함수 | 설명 |
|---|---|
| fill_n(first, count, value) | first부터 시작하여 count개의 요소를 value로 채움 |