swap函数
语法:
1 |
void swap(set<_Key,_Compare,_Alloc>& __x); |
swap()交换两个集合变量
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
/** * @brief Swaps data with another %set. * @param x A %set of the same element and allocator types. * * This exchanges the elements between two sets in constant time. * (It is only swapping a pointer, an integer, and an instance of * the @c Compare type (which itself is often stateless and empty), so it * should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(s1,s2) will feed to this function. */ void swap(set<_Key,_Compare,_Alloc>& __x) { _M_t.swap(__x._M_t); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <set> using namespace std; int main() { set<int> s1,s2; s1.insert(10); s1.insert(12); s1.insert(13); s1.insert(9); s2.insert(1); s2.insert(2); s2.insert(5); s2.insert(4); s2.insert(6); cout<<"s1集合中元素:"<<endl; set<int>::iterator iter = s1.begin(); for(iter;iter!=s1.end();iter++){ cout<<*iter<<" "; } cout<<endl; cout<<"s2集合中元素:"<<endl; iter = s2.begin(); for(iter;iter!=s2.end();iter++){ cout<<*iter<<" "; } cout<<endl; s1.swap(s2); //交换两集合 cout<<"交换后s1集合中元素:"<<endl; iter = s1.begin(); for(iter;iter!=s1.end();iter++){ cout<<*iter<<" "; } cout<<endl; cout<<"交换后s2集合中元素:"<<endl; iter = s2.begin(); for(iter;iter!=s2.end();iter++){ cout<<*iter<<" "; } cout<<endl; } |
测试结果:
1 2 3 4 5 6 7 8 |
s1集合中元素: 9 10 12 13 s2集合中元素: 1 2 4 5 6 交换后s1集合中元素: 1 2 4 5 6 交换后s2集合中元素: 9 10 12 13 |