Open In App

list::swap() in C++ STL

Last Updated : 28 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.

list::swap()

This function is used to swap the contents of one list with another list of same type and size.

Syntax :

listname1.swap(listname2)
Parameters :
The name of the lists with which
the contents have to be swapped.
Result :
All the elements of the 2 list are swapped.

Examples:

Input  : mylist1 = {1, 2, 3, 4}
mylist2 = {3, 5, 7, 9}
mylist1.swap(mylist2);
Output : mylist1 = {3, 5, 7, 9}
mylist2 = {1, 2, 3, 4}
Input : mylist1 = {1, 3, 5, 7}
mylist2 = {2, 4, 6, 8}
mylist1.swap(mylist2);
Output : mylist1 = {2, 4, 6, 8}
mylist2 = {1, 3, 5, 7}

Errors and Exceptions

1. It throws an error if the lists are not of the same type.

2. It has a basic no exception throw guarantee otherwise. 

CPP




// CPP program to illustrate
// Implementation of swap() function
#include <iostream>
#include <list>
using namespace std;
 
int main()
{
 // list container declaration
 list<int> mylist1{ 1, 2, 3, 4 };
 list<int> mylist2{ 3, 5, 7, 9 };
 
 // using swap() function to
 //swap elements of lists
 mylist1.swap(mylist2);
 
 // printing the first list
 cout << "mylist1 = ";
 for (auto it = mylist1.begin();
   it != mylist1.end(); ++it)
  cout << ' ' << *it;
 
 // printing the second list
 cout << endl
  << "mylist2 = ";
 for (auto it = mylist2.begin();
   it != mylist2.end(); ++it)
  cout << ' ' << *it;
 return 0;
}


Output:

mylist1 = 3 5 7 9 
mylist2 = 1 2 3 4

Time Complexity: O(n)
Auxiliary Space: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads