C ++ swap()函数用于交换(或替换)两个集合的内容,但是两个集合的类型必须相同,尽管大小可能有所不同。
void swap (set& x);
x:设置与之交换内容的容器。
没有
不变。
引用两个集合容器中的元素的所有引用,迭代器和指针都保持有效,但是现在引用另一个集合容器中的元素并在其中进行迭代。
容器和x均被修改。
如果抛出异常,则对容器没有影响。
让我们看一个简单的示例,将一组元素交换为另一组元素:
#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具有五个元素,而m2为空。当您将m1交换为m2时,m1的所有元素都将交换为m2。
让我们看一个简单的示例来交换两组内容:
#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 << "第一个集合包含:";
for (set<int>::iterator it = first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "第二个集合包含:";
for (set<int>::iterator it = second.begin(); it!=second.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
输出:
第一个集合包含: 40 50 60
第二个集合包含: 10 20 30
让我们看一个简单的示例来交换两个集合的内容:
#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()函数用于交换两个集合的内容。
让我们看一个简单的实例:
#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的成员函数版本
s1.swap( s2 );
cout << "与s2交换后,列表s1为:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
// 这是swap的专用模板版本
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.