C++ Deque swap()函数将给定双端队列的内容与传递给相同类型参数的双端队列进行交换。
void swap(deque& second);
second :这是另一个双端队列集合,其内容将与给定的双端队列交换。
它不返回任何值。
让我们看一个简单的例子
#include <iostream> #include<deque> using namespace std; int main() { deque<string> str={"C is a programming language"}; deque<string> str1={"java is a programming language"}; str.swap(str1); deque<string>::iterator itr=str.begin(); deque<string>::iterator itr1=str1.begin(); cout<<"After swapping,value of str is: "<<*itr; cout<<'\n'; cout<<"After swapping,value of str1 is: "<<*itr1; return 0; }
输出:
After swapping,value of str is: java is a programming language After swapping,value of str1 is: C is a programming language
在此示例中,swap()函数交换str和str1的内容。现在,str包含" java是一种编程语言",而str1包含" C是一种编程语言"。
让我们看一个简单的例子,当两个双端队列的类型不同时。
#include <iostream> #include<deque> using namespace std; int main() { deque<char> c={'m','a','n','g','o'}; deque<int> s={1 ,2,3,4,5}; c.swap(s); return 0; }
输出:
error: no matching function for call to 'std::deque<char>::swap(std::deque<int>&)
在此示例中,swap()函数将引发错误,因为两个双端队列的类型不同。
让我们看一个简单的例子,当大小不同时。
#include <iostream> #include<deque> using namespace std; int main() { deque<int> first={1,2,3,4}; deque<int> second={10,20,30,40,50}; deque<int>::iterator itr; first.swap(second); cout<<"Content of first deque:"; for(itr=first.begin();itr!=first.end();++itr) cout<<*itr<<" "; cout<<'\n'; cout<<"Content of second deque:"; for(itr=second.begin();itr!=second.end();++itr) cout<<*itr<<" "; return 0; }
输出:
Content of first deque:10 20 30 40 50 Content of second deque:1 2 3 4
在此示例中,swap()函数将第一个双端队列的内容交换为第二个双端队列。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)