C ++ swap()函數(shù)用于交換(或替換)兩個(gè)集合的內(nèi)容,但是兩個(gè)集合的類(lèi)型必須相同,盡管大小可能有所不同。
void swap (set& x);
x:設(shè)置與之交換內(nèi)容的容器。
沒(méi)有
不變。
引用兩個(gè)集合容器中的元素的所有引用,迭代器和指針都保持有效,但是現(xiàn)在引用另一個(gè)集合容器中的元素并在其中進(jìn)行迭代。
容器和x均被修改。
如果拋出異常,則對(duì)容器沒(méi)有影響。
讓我們看一個(gè)簡(jiǎn)單的示例,將一組元素交換為另一組元素:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<int> m1 = {1,2,3,4,5};
set<int> m2;
m2.swap(m1);
cout << "集合包含以下元素" << endl;
for (auto it = m2.begin(); it != m2.end(); ++it)
cout << *it<< endl;
return 0;
}輸出:
集合包含以下元素 1 2 3 4 5
在上面的示例中,集合m1具有五個(gè)元素,而m2為空。當(dāng)您將m1交換為m2時(shí),m1的所有元素都將交換為m2。
讓我們看一個(gè)簡(jiǎn)單的示例來(lái)交換兩組內(nèi)容:
#include <iostream>
#include <set>
using namespace std;
int main () {
int myints[] = {10,20,30,40,50,60};
set<int> first (myints,myints+3);
set<int> second (myints+3,myints+6);
first.swap(second);
cout << "第一個(gè)集合包含:";
for (set<int>::iterator it = first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "第二個(gè)集合包含:";
for (set<int>::iterator it = second.begin(); it!=second.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}輸出:
第一個(gè)集合包含: 40 50 60 第二個(gè)集合包含: 10 20 30
讓我們看一個(gè)簡(jiǎn)單的示例來(lái)交換兩個(gè)集合的內(nèi)容:
#include<iostream>
#include<set>
using namespace std;
int main()
{
// 取任意兩組集合
set<char> set1, set2;
set1 = {'a','b','c','d'};
set2 = {'x','y','z'};
// 交換集合元素
swap(set1, set2);
// 打印集合的元素
cout << "set1:\n";
for (auto it = set1.begin(); it != set1.end(); it++)
cout << "\t" << *it<< '\n';
cout << "set2:\n";
for (auto it = set2.begin(); it != set2.end(); it++)
cout << "\t" << *it<< '\n';
return 0;
}輸出:
set1: x y z set2: a b c d
在上面的示例中,另一種形式的swap()函數(shù)用于交換兩個(gè)集合的內(nèi)容。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int> s1, s2, s3;
set <int>::iterator s1_Iter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
s2.insert( 100 );
s2.insert( 200 );
s3.insert( 300 );
cout << "原始集合s1是:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
// 這是swap的成員函數(shù)版本
s1.swap( s2 );
cout << "與s2交換后,列表s1為:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
// 這是swap的專(zhuān)用模板版本
swap( s1, s3 );
cout << "在與s3交換之后,列表s1是:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
}輸出:
原始集合s1是: 10 20 30. 與s2交換后,列表s1為: 100 200. 在與s3交換之后,列表s1是: 300.