C++자료구조

[C++] fill함수

템플릿 함수

template <class ForwardIterator, class T>

  void fill (ForwardIterator first, ForwardIterator last, const T& val);

value(값)으로 범위를 Fill

range 범위[first,last)안에 있는 모든 elements에 val(값)을 할당.

위의 템플릿함수는 아래와 같다:

template <class ForwardIterator, class T>
  void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
  while (first != last) {
    *first = val;
    ++first;
  }
}

 

매개변수

-first, last

처음과 마지막의 iterator(커서/포인터)로 T데이터타입의 값할당을 elements의 순차적위치로 보여준다.

그래서 first와 last사이의 모든 elements를 모두 포함하는 범위를 가진다. 

단, first가 가리키는 element는 포함하지만 last가 가리키는 element는 포함하지 않는다.

-val

filled range(채워진 범위) 안의 elements를 할당하는 값

 

리턴값

없음

 

예제

// fill algorithm example
#include <iostream>     // std::cout
#include <algorithm>    // std::fill
#include <vector>       // std::vector

int main () {
  std::vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0

  std::fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
  std::fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

결과

myvector contains: 5 5 5 8 8 8 0 0

복잡도

first와 last사이의 직선의 거리(매 element마다 값을 할당하므로)

 

예외처리

iterator을 가진 메소드나 element가 throw하면 throw함

유효하지 않은 인자가 정의 되지 않은 동작을 하는경우

 

 

 

참고자료.

http://www.cplusplus.com/reference/algorithm/fill/