English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ The List swap() function swaps two lists of the same type, but the size can be different.
void swap(list& x);
x:This is another list to be swapped with the given list.
It does not return any value.
An error will occur if the types of the two lists are not the same.
Let's look at a simple example where both lists have the same type and size.
#include iostream> #include<list> using namespace std; int main() { std::list<char> li={"+,-,*,",@",} list<char> li1={'j','a','v','a'}; std::cout << "Initially, the content of list li is : "; for(list<char> :: iterator itr=li.begin();itr!=li.end();++itr) cout<<*itr; std::cout << '\n' << "Initially, list li1The content is : "; for(list<char> :: iterator itr=li1.begin();itr!=li1.end();++itr) cout<<*itr; li.swap(li1); cout << '\n'; cout<<"After the swap, the content of list li is : "; for(list<char> :: iterator itr=li.begin();itr!=li.end();++itr) cout<<*itr; cout << '\n'; cout<<"After the swap, list li1The content is : "; for(list<char> :: iterator itr=li1.begin();itr!=li1.end();++itr) cout<<*itr; return 0; }
Output:
Initially, the content of list li is : +-*@ Initially, list li1The content is : java After the swap, the content of list li is : java After the swap, the content of list li1The content is : +-*@
In this example, the swap() function will swap the contents of list li with list li1Swap.
Let's look at a simple example, when both lists are of different types.
#include iostream> #include<list> using namespace std; int main() { std::list<char> li={'P','H','P'}; list<int> li1={1,2,3}; li.swap(li1); cout << '\n'; return 0; }
Output:
error : no matching call for list::swap(list&).
In this example, both lists are of different types. Therefore, the function swap() will cause an error, that is: list :: swap(list&) does not have a matching call.