C ++ Deque swap()函数将给定双端队列的内容与传递给相同类型参数的双端队列进行交换。
双端队列的类型必须相同。
双端队列的大小允许不等。
void swap(deque& second);
second:这是另一个双端队列容器,其内容将与给定的双端队列交换。
它不返回任何值。
让我们看一个简单的实例
#include <iostream>
#include<deque>
using namespace std;
int main()
{
deque<string> str={"C是一种编程语言"};
deque<string> str1={"java是一种编程语言"};
str.swap(str1);
deque<string>::iterator itr=str.begin();
deque<string>::iterator itr1=str1.begin();
cout<<"交换后,str的值为: "<<*itr;
cout<<'\n';
cout<<"交换后,str1的值为: "<<*itr1;
return 0;
}输出:
交换后,str的值为: java是一种编程语言 交换后,str1的值为: C是一种编程语言
在此示例中,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<<"第一双端队列的内容:";
for(itr=first.begin();itr!=first.end();++itr)
cout<<*itr<<" ";
cout<<'\n';
cout<<"第二双端队列的内容:";
for(itr=second.begin();itr!=second.end();++itr)
cout<<*itr<<" ";
return 0;
}输出:
第一双端队列的内容:10 20 30 40 50 第二双端队列的内容:1 2 3 4
在此示例中,swap()函数将第一个双端队列的内容交换为第二个双端队列。