C++ STL fill_n / fill
fill_n : 설정한 값으로 시퀀스 할당 하기.
#include <algorithm>
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val)
{
while(n > 0)
{
*first = val;
++first;
--n;
}
return first; // since C++11
}
first에 설정한 오브젝트에 N의 사이즈 만큼 Val에 설정한 값으로 할당 한다.
대체적으로 배열 초기화시 원하는 값으로 초기화 할때 사용 하는 STL 이다.
const int ARRAY_MAX_SIZE = 10;
int nArrayValue[ARRAY_MAX_SIZE] = { 0, };
int nFillValue = 255;
// nArrayValue 배열 10개의 int 값을 255로 할당한다.
std::fill_n( nArrayValue, ARRAY_MAX_SIZE, nFillValue );
그 외,
fill 도 있다.
#include <algorithm>
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
while (first != last)
{
*first = val;
++first;
}
}
first에 오브젝트 처음 인덱스, last에 오브젝트 마지막 인덱스를 설정하고 Val에 값을 할당한다.
vector<int> vecFillList;
vecFillList.push_back( 1 );
vecFillList.push_back( 2 );
vecFillList.push_back( 3 );
vecFillList.push_back( 4 );
vecFillList.push_back( 5 );
int nFillValue = 255;
// vecFillList에 사이즈 만큼 255로 할당한다.
std::fill( vecFillList.begin(), vecFillList.end(), nFillValue );
// 사이즈를 임의로 설정하여 할당도 가능.
std::fill( vecFillList.begin() + 2, vecFillList.end(), nFillValue );
참조 :
cplusplus.com/reference/algorithm/fill
cplusplus.com/reference/algorithm/fill_n