list::swap() in C++ STL


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.