forward_list::swap() in C++ STL


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 

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.

Article Tags :
C++
Practice Tags :