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

C++ List splice() usage and example

C++ List (List)

C ++ The list concatenation function is used to transfer elements from the list y to the specified position in the list container, which causes the size of both lists to change.

Syntax

void splice(iterator pos, list& y); 
void splice(iterator pos, list& y, iterator pos1);
void splice(iterator pos, list& y, iterator first, iterator last);

Parameter

y: It is a list object of the same content transmission type.

pos: It defines the position where the y element is inserted.

pos1:pos1The elements pointed to will be transmitted.

(first, last): It defines the range of elements to be transmitted.

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> li1={5,6,7,8};
  list<int>::iterator itr=li.begin();
  li.splice(itr,li1);
  for(list<int>::iterator itr=li.begin();itr!=li.end();++itr)
  std::cout << *itr << " ";
  return 0;
}

Output:

5 6 7 8 1 2 3 4

Example2

Let's look at a simple example

#include<iostream>
#include<list>
using namespace std;
int main()
{
  list<int> li={9,11,12,13};
  list<int> li1={10,6,7,8};
  list<int>::iterator itr=li.begin();
 list<int>::iterator itr1=li1.begin();
  ++itr;
  li.splice(itr,li1,itr1);
  for(list<int>::iterator itr=li.begin();itr!=li.end();++itr)
  std::cout << *itr << " ";
  return 0;
}

Output:

9 10 11 12 13

Example3

Let's look at a simple example

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

Output:

java is a programming language

C++ List (List)