List Assign Function

C++ List assign

C++ List assign function assigns new contents to the list container and replaces the old one with a new one.

Syntax

Example

void assign(InputIterator first, OutputIterator last);
void assign(size_type n, value_type val);

Parameter

first,last : It defines the range of the elements that are to be copied.

n : It specifies the new size of the container.

val : New value which is to added in a newly constructed space.

Return value

It does not return any value.

Example 1

Let's see a simple example

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
  list<int> li={1,2,3,4};
  list<int>::iterator itr;
  li.assign(3,10);
  for(itr=li.begin();itr!=li.end();++itr)
  cout<<*itr<<" ";
  return 0;
 }

Output:

Output

10 10 10

In this example, assign function replaces the old content with a new content. It assigns '10' value 3 times in the list container.

Example 2

Let's see a simple example

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
  list<char> first={'C','+','+'};
  list<char> second;
  list<char>::iterator itr;
  second.assign(first.begin(),first.end());
  for(itr=second.begin();itr!=second.end();++itr)
  cout<<*itr;
  return 0;
}

Output:

In this example, assign function assigns the first list to the second list.

Input Required

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