Difference between fill() and fill_n() functions in C++ STL

Fill() and Fill_n() are two functions in the C++ Standard Template Library (STL) that are used to fill a range of elements in a container with a given value. However, they differ somewhat in terms of functionality and use. In this article, we will discuss difference between Fill() and Fill_n() method in C++. But before discussing their differences, we must know about the Fill() and Fill_n() method.

What is the std::fill() method?

  • The specified value is filled in the range [first, last) by std::fill().
  • It requires two iterators, first and last, which indicate the range that needs to be filled and a value that will be applied to each element.

Syntax:

It has the following syntax:

Example:

Let us take an example to illustrate the std::fill() method in C++.

Output:

Difference between fill() and fill_n() functions in C++ STL

What is the std::fill_n() method?

  • The std::fill_n() method inserts the given value into the first count elements, beginning with the iterator.
  • Filling the elements requires an iterator that points to the beginning position, the number of elements to fill (count), and a value.

Syntax:

It has the following syntax:

Example:

Let us take an example to illustrate the std::fill_n() method in C++.

Output:

Difference between fill() and fill_n() functions in C++ STL

Main differences between fill() and fill_n() method:

Difference between fill() and fill_n() functions in C++ STL

There are several differences between the fill() and fill_n() method. Some main differences between these methods are as follows:

S.Nofill()fill_n()
1.It sets the given value to every array element.It is employed to give a new value to a predetermined number of elements in a range that start at a specific element.
2.Its syntax is -:
void fill(ForwardIterator first, ForwardIterator last, const value_type &val);
Its syntax is -:
In C++ 98:
void fill_n (OutputIterator first, Size n, const T& val);
From C++11 onwards:
OutputIterator fill_n (OutputIterator first, Size n, const T& val);
3.There is no value returned by it.It returns an iterator pointing to the element that comes after the final element to be filled (in C++ 11).
(In C++ 98) yields null.
4.O(N) is the time complexity of it.O(N) is the time complexity of it.





Latest Courses