Home » C++ STL

std::fill() function with example in C++ STL

C++ STL | std::fill() function: Here, we are going to learn about the fill() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 21, 2019

C++ STL std::fill() function

fill() function is a library function of algorithm header, it is used to assign a value to the all elements within a given range of a container, it accepts iterators pointing to the starting and ending position in the container and a value to be assigned to the elements within the given range, and assigns the value.

Note: To use fill() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.

Syntax of std::fill() function

    std::fill(iterator start, iterator end, value);

Parameter(s):

  • iterator start, iterator end – these are the iterator positions pointing to the ranges in the container.
  • value – a value of the same type to be assigned to the all elements.

Return value: void – it returns noting.

Example:

    Input:
    vector<int> v(10);
    
    //filling all elements with -1
    fill(v.begin(), v.end(), -1);
    
    Output:
    -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

C++ STL program to demonstrate use of std::fill() function

In this program, we are going to fill the elements of a vector.

//C++ STL program to demonstrate use of
//std::fill() function
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
    //vector
    vector<int> v(10);

    //filling all elements with -1
    fill(v.begin(), v.end(), -1);

    //printing vector elements
    cout << "v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //filling initial 3 elements with 100
    fill(v.begin(), v.begin() + 3, 100);

    //printing vector elements
    cout << "v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    //filling rest of the elements with 200
    fill(v.begin() + 3, v.end(), 200);

    //printing vector elements
    cout << "v: ";
    for (int x : v)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

v: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
v: 100 100 100 -1 -1 -1 -1 -1 -1 -1
v: 100 100 100 200 200 200 200 200 200 200

Reference: C++ std::fill()






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.