Difference Between Fill And Fill N Functions In C++ STL

Fill and Filln 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 Filln 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

template<class ForwardIt, class T>
void fill(ForwardIt first, ForwardIt last, const T& value);

Example:

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

Example

#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {7, 9, 8, 1, 1};
std::fill(numbers.begin(), numbers.end(), 5);
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}

Output:

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 thacpp tutorials to the beginning position, the number of elements to fill (count), and a value.
  • Syntax:

It has the following syntax:

Example

template<class OutputIt, class Size, class T>
OutputIt fill_n(OutputIt first, Size count, const T& value);

Example:

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

Example

#include <algorithm>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {7, 9, 8, 1, 1};
std::fill_n(numbers.begin(), 3, 5);
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}

Output:

Main differences between fill and fill_n method:

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

S.No fill() 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 filln (OutputIterator first, Size n, const T& val);From C++11 onwards:OutputIterator filln (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.

Input Required

This code uses input(). Please provide values below: