In the C++ programming language, the Standard Template Library (STL) includes the std::list container that implements the doubly linked list. The list::swap function is a member function of the std::list container. The swap function is mainly used to swap the contents of a list with another list of the same type in constant time, O(1). Instead of creating the class list objects to copy/move each element individually, the swap function simply switches the internal pointers of two lists.
In C++, the swap function ignores the list size while swapping the list elements, but it verifies the list type. If the list type is different, it will raise an error. The return type of this function is void, which means that it does not return any value. It changes the list size if required.
Syntax:
It has the following syntax:
// Member function syntax
list1.swap(list2);
// Non-member function syntax (in <algorithm>)
swap(list1, list2);
</algorithm>
In this syntax,
- The list1 and list2 must both be std::list objects (with the same data type and allocator).
Return Value: The swap function does not return any value. It returns only void.
C++ Simple List swap Function Example
Let us take an example to demonstrate the difference before and after swapping elements from one list to another list using the swap function in C++.
Example
#include <iostream>
#include <list>
using namespace std; //using standard namespace
int main() { //main function
// Create two lists
list<int> list1 = {10, 20, 30};
list<int> list2 = {100, 200, 300, 400};
cout << "Before swapping:" << endl;
cout << "list1: ";
for (int x : list1) cout << x << " ";
cout << "\nlist2: ";
for (int x : list2) cout << x << " ";
cout << endl;
// Swap contents of list1 and list2
list1.swap(list2);
cout << "\nAfter swapping:" << endl;
cout << "list1: ";
for (int x : list1) cout << x << " ";
cout << "\nlist2: ";
for (int x : list2) cout << x << " ";
cout << endl;
return 0;
}
Output:
Before swapping:
list1: 10 20 30
list2: 100 200 300 400
After swapping:
list1: 100 200 300 400
list2: 10 20 30
Explanation:
In this example, we have created two lists with their elements: List 1 {10, 20, 30} and List 2{100, 200, 300, 400}. First, it will print out the list contents before swapping. Upon executing the line list1.swap(list2), the items in lists 1 and 2 are reversed. After swapping, the original material in list 1 becomes the new material for list 2, and the original material in list 2 becomes the new material for list 1. This operation is performed in a constant time (O(1)).
Key Points about the List Swap Function in C++
There are several key points about the list swap function in C++. Some of them are as follows:
- In C++, the swap function is a member function of the list container that allows us to swap the contents of two lists of the same type.
- The swap function in C++ is exception-safe and doesn't throw any exceptions.
- It is mainly utilized for data exchange, resetting containers, and implementing move semantics.
- In C++, both lists should be of the same data type that can be swapped with another effectively.
- When we swap the lists, the list elements are not copied or moved individually. It exchanges only the internal data structures.
- In C++, if the lists are of different sizes, the swap function completely exchanges their content effectively.
Types of errors or exceptions occur in the C++ List Swap
There are several types of errors and exceptions that occur in the list swap function in C++. Some of them are as follows:
1) Type Mismatch Error (Compilation Error)
We cannot swap two lists that are of different types.
list<int> l1;
list<string> l2;
l1.swap(l2); // Error: different data types
The compiler generates a type mismatch error because the two lists must be of the same type.
2) Allocator Mismatch Error (Compilation/Linking Error)
If both lists were created with different allocators, the swap function can fail or cause unpredictable behavior. The two lists must have the same type of allocator, the same way type is checked for lists themselves.
3) Exception Safety
In C++, the list::swap member function does not throw (noexcept in modern C++). Therefore, we do not have to worry about runtime exceptions (such as std::bad_alloc) for several operations and functions in the STL.
4) Logic Errors (Programmer Errors)
In C++, it is possible to use the swap function incorrectly, which results in logic errors, not compilation/runtime errors.
5) Infrequently Occurring Behavior
In general, there is no reason to swap a list with itself, but if we try, the compiler will allow it (list1.swap(list1).
C++ Example for Swapping Two Lists in C++ Using the list::swap function
Let us take an example to illustrate how to swap two lists using the list::swap function in C++.
Example
#include <iostream>
#include <list>
#include <string>
using namespace std; //using standard namespace
int main() { //main function
// Create two lists of strings
list<string> fruits = {"Apple,", "Banana,", "Mango"};
list<string> vegetables = {"Carrot,", "Potato,", "Tomato,", "Onion"};
cout << "Before swapping:" << endl;
cout << "Fruits: ";
for (const string &f : fruits) cout << f << " ";
cout << "\nVegetables: ";
for (const string &v : vegetables) cout << v << " ";
cout << endl;
// Swap contents of the two lists
fruits.swap(vegetables);
cout << "\nAfter swapping:" << endl;
cout << "Fruits: ";
for (const string &f : fruits) cout << f << " ";
cout << "\nVegetables: ";
for (const string &v : vegetables) cout << v << " ";
cout << endl;
return 0;
}
Output:
Before swapping:
Fruits: Apple, Banana, Mango
Vegetables: Carrot, Potato, Tomato, Onion
After swapping:
Fruits: Carrot, Potato, Tomato, Onion
Vegetables: Apple, Banana, Mango
Explanation:
In this example, we have taken two different lists of fruits and vegetables. First, this program will print the content of these two lists before swapping. When we execute the Fruits.swap(vegetables) statement, both lists are switched in a fixed amount of time. After swapping, the names of every fruit will show up in the vegetables list, and the names of every vegetable will show up in the fruits.
Swapping List Elements using the swap function in C++
Let us take another example to illustrate how to swap list elements using the swap function in C++.
Example
#include <iostream>
#include<list>
using namespace std; //using standard namespace
int main() //main function
{
std::list<char> li={'+','-','*','@'};
list<char> li1={'L','i','s','t'};
std::cout << "Initially, the content of the list li is: ";
for(list<char> :: iterator itr=li.begin();itr!=li.end();++itr)
cout<<*itr;
std::cout << '\n'<<"Initially,content of the list li1 is: ";
for(list<char> :: iterator itr=li1.begin();itr!=li1.end();++itr)
cout<<*itr;
li.swap(li1);
cout<<'\n';
cout<<"After swapping, the content of the list li is: ";
for(list<char> :: iterator itr=li.begin();itr!=li.end();++itr)
cout<<*itr;
cout<<'\n';
cout<<"After swapping, the content of the list li1 is: ";
for(list<char> :: iterator itr=li1.begin();itr!=li1.end();++itr)
cout<<*itr;
return 0;
}
Output:
Initially, the content of the list li is: +-*@
Initially, the content of the list li1 is: List
After swapping, the content of the list li is: List
After swapping, the content of the list li1 is: +-*@
Explanation:
In this example, we have created two character lists: li containing '+', '-', '*', '@', and li1 containing 'L', 'i', 's', 't'. First, the program will print the contents of both lists before swapping. When the li.swap(li1) statement is executed, the elements of the two lists are exchanged in constant time (O(1)). After the swap operation, li contains the original elements of li1, and li1 contains the original elements of li.
Conclusion
In conclusion, the list::swap function is a simple that is used to swap two lists of the same type. Instead of copying or moving each element; it only swaps internal pointers, which takes constant time, O(1).
Moreover, the list::swap function also preserves iterators and references, which remain valid and point to the correct contents after the swap. It is also useful when reorganizing, replacing, or swapping entire lists without the need to worry about performance handling.
C++ List Swap Function FAQ's
1) Does the list::swap function copy elements from one list to the next in C
No, the swap function also swaps internal pointers, which is incredibly faster (O(1) time).
2) Can we swap two lists that differ in size in C++?
Yes, the swap function exchanges all contents of both lists that differ in size.
3) What happens to the iterators and references after swapping in C++?
In C++, they remain valid, bucpp tutorial to the other swapped list's contents.
4) Describe the differences between swap(list1,list2) and list1.swap(list2)?
The main difference between the swap(list1,list2) and list1.swap is that the swap(list1,list2) function is a non-member function that calls the member function internally. On the other hand, the list1.swap function is a member function that does the same thing.
5) Is the list::swap function faster than moving elements from one list to another in C++?
Yes, the list::swap function is faster than moving elements from one list to another because it is swapping internal data structures, and not copying one element at a time.