📅  最后修改于: 2020-10-20 08:01:15             🧑  作者: Mango
C++ swap()函数用于交换(或交换)两个集合的内容,但是两个集合的类型必须相同,尽管大小可能有所不同。
void swap (set& x);
x:Set.与之交换内容的容器。
没有
不变。
引用两个集合容器中的元素的所有引用,迭代器和指针均保持有效,但是现在引用另一个集合容器中的元素,并在其中进行迭代。
容器和x均被修改。
如果抛出异常,则对容器没有影响。
让我们看一个简单的示例,将一组元素交换为另一组:
#include
#include
using namespace std;
int main(void) {
set m1 = {1,2,3,4,5};
set 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。
让我们看一个简单的示例来交换两组内容:
#include
#include
using namespace std;
int main () {
int myints[] = {10,20,30,40,50,60};
set first (myints,myints+3);
set second (myints+3,myints+6);
first.swap(second);
cout << "first set contains:";
for (set::iterator it = first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "second set contains:";
for (set::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
让我们看一个简单的示例来交换两个集合的内容:
#include
#include
using namespace std;
int main()
{
// Take any two sets
set 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()函数用于交换两个集合的内容。
让我们看一个简单的例子:
#include
#include
int main( )
{
using namespace std;
set s1, s2, s3;
set ::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.