English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ List assign() Usage and Example

C++ List (List)

C ++ The List Assign() function assigns new content to the list container and replaces the old container with the new one.

Syntax

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

Parameters

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

n:Specify the new size of the container.

val:The new value to be added to the new list.

Return value

It does not return any value.

Example1

Let's look at a simple 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:

10 10 10

In this example, the assign() function replaces the old content with new content. It allocates3the 10”Value.”

Example2

Let's look at a simple 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:

C++

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

C++ List (List)