forward_list assign() function in C++ STL

The forward_list::assign() is a function in C++ STL which assigns new content to a forward list, replacing its current content and adjusting its size as required.

Syntax:

Version 1:forward_list_name.assign(iterator it1, iterator it2)
Version 2:forward_list_name.assign(int n, val)
Version 3:forward_list_name.assign(initializer_list li)

Parameters: This function accepts different parameters in different version which are discussed below:

Return Value This function does not return any value.

The three versions of the function forward_list::assign is illustrated in the following programs:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP code to illustrate the
// forward_list::assign() function
  
#include <forward_list>
#include <iostream>
using namespace std;
  
int main()
{
    forward_list<int> sample1;
    forward_list<int> sample2;
  
    // Create n elements in
    // sample1 and initialize all
    // Of them with 3
    sample1.assign(5, 3);
  
    // Initilize sample2 with elements in
    // the range [sample1.begin(), sample1.end)
    sample2.assign(sample1.begin(), sample1.end());
  
    // Display sample1
    cout << "sample1: ";
    for (int& x : sample1)
        cout << x << " ";
  
    cout << endl;
  
    // Display sample2
    cout << "sample2: ";
    for (int& x : sample2)
        cout << x << " ";
}
chevron_right

Output:
sample1: 3 3 3 3 3 
sample2: 3 3 3 3 3

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP code to illustrate the
// forward_list::assign() function
  
#include <forward_list>
#include <iostream>
using namespace std;
  
int main()
{
    forward_list<int> sample;
  
    // Initialize sample with an
    // Initialization list
    sample.assign({ 4, 5, 7, 8, 9, 45 });
  
    // Display sample
    cout << "sample: ";
    for (int& x : sample)
        cout << x << " ";
}
chevron_right

Output:
sample: 4 5 7 8 9 45

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.




Article Tags :
C++
Practice Tags :