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.
3. It has a basic no exception throw guarantee otherwise.
CPP
#include <iostream>
#include <list>
using namespace std;
int main()
{
list< int > mylist1{ 1, 2, 3, 4 };
list< int > mylist2{ 3, 5, 7, 9 };
mylist1.swap(mylist2);
cout << "mylist1 = " ;
for ( auto it = mylist1.begin();
it != mylist1.end(); ++it)
cout << ' ' << *it;
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
Time Complexity: O(n)
Auxiliary Space: O(1)