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 


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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




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

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.






User Actions