💡 퀵 접속: cpp.kr/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(first, last, value) | [first, last) 범위의 모든 요소를 value로 채움 |