C++ std swap()
C++ std swap(set)是C++ 中set的非成员函数 。这用于交换(或交换)两个集合(即x和y)的内容,但两个集合的类型必须相同,尽管大小可能会有所不同。
语法
template <class T, class Compare, class Alloc>
void swap (set<T,Compare,Alloc>& x, set<T,Compare,Alloc>& y);
参数
x : 第一个设置对象。
y : 第二个设置对象
返回值
无
复杂度
常量。
迭代器有效性
引用两个容器中元素的所有迭代器,引用和指针均保持有效。
请注意,最终迭代器未引用
数据竞争
容器x和y均被修改。
该调用未访问任何包含的元素。
异常安全
此函数不会引发异常。
示例1
让我们看一个简单的示例,将一组元素交换为另一组:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m1 = {'a','b','c','d'};
set<char> m2;
swap(m1, m2);
cout << "Set contains following elements" << endl;
for (auto it = m2.begin(); it != m2.end(); ++it)
cout << *it<< endl;
return 0;
}
输出:
Set contains following elements
a
b
c
d
在上面的示例中,集合m1具有五个元素,而m2为空。当您将m1交换为m2时,m1的所有元素都将交换为m2、
示例2
让我们看一个简单的示例来交换两组内容:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> set1,set2;
set1= {100,200};
set2 = {110, 220, 330};
swap(set1,set2);
cout << "set1 contains:\n";
for (set<int>::iterator it=set1.begin(); it!=set1.end(); ++it)
cout << *it<< '\n';
cout << "set2 contains:\n";
for (set<int>::iterator it=set2.begin(); it!=set2.end(); ++it)
cout << *it<< '\n';
return 0;
}
输出:
set1 contains:
110
220
330
set2 contains:
100
200
在上面的示例中,两个集合的内容,即set1和set2相互交换。
示例3
让我们看一个简单的示例交换两组内容:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
int myints[]={12,75,10,32,20,25};
set<int> first (myints,myints+3); // 10,12,75
set<int> second (myints+3,myints+6); // 20,25,32
swap(first,second);
cout << "first contains:";
for (set<int>::iterator it=first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "second contains:";
for (set<int>::iterator it=second.begin(); it!=second.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
输出:
first contains: 20 25 32
second contains: 10 12 75
示例4
让我们看一个简单的示例:
#include <iostream>
#include <string>
#include <set>
using namespace std;
void show(const char *msg, set<int> mp);
int main() {
set<int> m1, m2;
m1.insert(100);
m1.insert(300);
m1.insert(200);
// Exchange the contents of m1 and m2.
cout << "Exchange m1 and m2.\n";
swap(m1,m2);
show("Contents of m2: ", m2);
show("Contents of m1: ", m1);
// Clear m1.
m1.clear();
if(m1.empty()) cout << "m1 is now empty.";
return 0;
}
// Display the contents of a set<string, int> by using an iterator.
void show(const char *msg, set<int> mp) {
set<int>::iterator itr;
cout << msg << endl;
for(itr=mp.begin(); itr != mp.end(); ++itr)
cout << " " << *itr<< endl;
cout << endl;
}
输出:
Exchange m1 and m2.
Contents of m2:
100
200
300
Contents of m1:
m1 is now empty.
在上面的示例中,将set m1的内容交换为set m2,并且在交换m1 set后已将其清除。