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

C++ List emplace() Usage and Example

C++ List (List)

C ++ The List emplace() function inserts a new element at the specified position, and the size of the list increases by one.

Syntax

iterator emplace(iterator pos, value_type val);

Parameter

pos:It defines the position where the new element is to be inserted.

val:The value to be inserted at the specified position.

Return Value

It returns an iterator pointing to the newly constructed element.

Example1

Let's look at a simple example of inserting a new element between the list elements.

#include<iostream>
#include<list>
using namespace std;
int main()
{
  list<char> li={'j','v','a'};
  list<char>::iterator itr=li.begin();
  ++itr;
  li.emplace(itr, 'a');
  for(itr=li.begin();itr!=li.end();++itr)
  cout <<*itr;
  return 0;
}

Output:

java

In this example, the emplace() function added a new character at the second position

Example2

Let's look at a simple example of adding a new element to the end of the list.

#include<iostream>
#include<list>
using namespace std;
int main()
{
  list<string> li={"java","is","a"};
  list<string>::iterator itr;
  li.emplace(li.end(),"programming language");
 for(itr=li.begin();itr!=li.end();++itr)
  cout <<*itr << "  ";
  return 0;
 
}

Output:

java is a programming language

In this example, the emplace() function adds a new string at the end of the list, that is, 'programming language'.

C++ List (List)