forward_list assign() function in C++ STL
Last Updated :
15 Jun, 2022
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:
- Iterator: The first version takes two iterators as parameters. New elements are constructed from each element in the range [it1, it2) i.e it includes all elements between it1 and it2 including the element dereferenced by it1 but excluding the element pointed by it2.
- n and val: In the second version n elements are created and each element is initialized with value val.
- Initializer_list: In the third version the new contents are created which are initialized with copies of the values passed as initializer list, in the same order.
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:
CPP
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
forward_list< int > sample1;
forward_list< int > sample2;
sample1.assign(5, 3);
sample2.assign(sample1.begin(), sample1.end());
cout << "sample1: " ;
for ( int & x : sample1)
cout << x << " " ;
cout << endl;
cout << "sample2: " ;
for ( int & x : sample2)
cout << x << " " ;
}
|
Output:
sample1: 3 3 3 3 3
sample2: 3 3 3 3 3
Program 2:
CPP
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
forward_list< int > sample;
sample.assign({ 4, 5, 7, 8, 9, 45 });
cout << "sample: " ;
for ( int & x : sample)
cout << x << " " ;
}
|
Output:
sample: 4 5 7 8 9 45
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...