C++ Set swap()
C++ " swap()函数用于交换(或交换)两个集合的内容,但是两个集合必须是相同的类型。
语法
参数
x : Set 容器以与之交换内容。
返回值
无
复杂度
常量。
迭代器有效性
全部在两个集合容器中引用元素的引用,迭代器和指针仍然有效,但是现在正在引用另一个集合容器中的元素,并在其中进行迭代。
数据竞争
容器和x均被修改。
异常安全性
如果引发异常,则对容器没有影响。
示例1
让我们看一下将一组元素交换为另一组的简单示例:
#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 << "Set contains following elements" << endl;
for (auto it = m2.begin(); it != m2.end(); ++it)
cout << *it<< endl;
return 0;
}
输出:
Set contains following elements
1
2
3
4
5
在上面的示例中,集合m1具有五个元素,而m2为空。当您将m1交换为m2时,m1的所有元素都将交换为m2、
示例2
让我们看一个简单的示例来交换两个集合的内容:
#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 << "first set contains:";
for (set<int>::iterator it = first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "second set contains:";
for (set<int>::iterator it = second.begin(); it!=second.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
输出:
first set contains: 40 50 60
second set contains: 10 20 30
示例3
让我们看一个简单的示例来交换两组内容:
#include<iostream>
#include<set>
using namespace std;
int main()
{
// Take any two sets
set<char> set1, set2;
set1 = {'a','b','c','d'};
set2 = {'x','y','z'};
// Swap elements of sets
swap(set1, set2);
// Print the elements of sets
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()函数用于交换两个集合的内容。
示例4
让我们看看简单的例子:
#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 << "The original set s1 is:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
// this is the member function version of swap
s1.swap( s2 );
cout << "After swapping with s2, list s1 is:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
// this is the specialized template version of swap
swap( s1, s3 );
cout << "After swapping with s3, list s1 is:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
}
输出:
The original set s1 is: 10 20 30.
After swapping with s2, list s1 is: 100 200.
After swapping with s3, list s1 is: 300.