Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

list::swap() in C++ STL

  • Last Updated : 12 Jan, 2018


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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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 throws an error if the lists are not of the same size.
2. It has a basic no exception throw guarantee otherwise.




// 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 



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!