Skip to content
Related Articles

Related Articles

Improve Article
forward_list::swap() in C++ STL
  • Last Updated : 26 Jul, 2018


Forward list in STL implements singly linked list. Introduced from C++11, forward lists are useful than other containers for insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from the list by the fact that forward list keeps track of the location of only next element while list keeps track to both next and previous elements.

forward_list::swap()

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

Syntax :

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

Examples:

Input  : myflist1 = {1, 2, 3, 4}
         myflist2 = {3, 5, 7, 9}
         myflist1.swap(myflist2);
Output : myflist1 = {3, 5, 7, 9}
         myflist2 = {1, 2, 3, 4}

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

Errors and Exceptions

1. It throws an error if the forward lists are not of the same type.
2. It throws an error if the forward 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 <forward_list>
#include <iostream>
using namespace std;
  
int main()
{
    // forward list container declaration
    forward_list<int> myflist1{ 1, 2, 3, 4 };
    forward_list<int> myflist2{ 3, 5, 7, 9 };
  
    // using swap() function to
    // swap elements of forward lists
    myflist1.swap(myflist2);
  
    // printing the first forward list
    cout << "myflist1 = ";
    for (auto it = myflist1.begin();
         it != myflist1.end(); ++it)
        cout << ' ' << *it;
  
    // printing the second forward list
    cout << endl
         << "myflist2 = ";
    for (auto it = myflist2.begin();
         it != myflist2.end(); ++it)
        cout << ' ' << *it;
    return 0;
}

Output:

myflist1 = 3 5 7 9 
myflist2 = 1 2 3 4 
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.



My Personal Notes arrow_drop_up
Recommended Articles
Page :