C++ swap()函数用于交换(或交换)两个集合的内容,但是两个集合都必须具有相同类型,尽管大小可能有所不同。
void swap (set& 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 << "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 <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
让我们看一个简单的示例来交换两个集合的内容:
#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()函数用于交换两个集合的内容。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-swap-function.html
来源:LearnFk无涯教程网
让我们看一个简单的例子:
#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.
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)