C++ STL中的multiset::swap()
Multisets是一种类似于set的关联容器,但不同的是它允许保存相同值的多个元素。
multiset::swap()
这个函数用于交换两个multisets的内容,但这两个sets的类型必须相同,尽管它们的大小可能不同。
语法:
multisetname1.swap(multisetname2)
参数:
需要交换内容的multiset的名字。
结果:
两个multiset的所有元素都被交换。
示例:
输入: multiset1 = {1, 2, 3, 4}
multiset2 = {5, 6, 7, 8}
multiset1.swap(multiset2);
输出: multiset1 = {5, 6, 7, 8}
multiset2 = {1, 2, 3, 4}
输入: multiset1 = {'a', 'b', 'c', 'd'}
multiset2 = {'w', 'x', 'y', 'z'}
multiset1.swap(multiset2);
输出: multiset1 = {'w', 'x', 'y', 'z'}
multiset2 = {'a', 'b', 'c', 'd'}
// INTEGER MULTISET EXAMPLE
// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 取两个multisets
multiset<int> multiset1{ 1, 2, 3, 4 };
multiset<int> multiset2{ 5, 6, 7, 8 };
// 交换multisets的元素
multiset1.swap(multiset2);
// 输出第一个multiset
cout << "multiset1 = ";
for (auto it = multiset1.begin();
it != multiset1.end(); ++it)
cout << ' ' << *it;
// 输出第二个multiset
cout << endl
<< "multiset2 = ";
for (auto it = multiset2.begin();
it != multiset2.end(); ++it)
cout << ' ' << *it;
return 0;
}
输出:
multiset1 = 5 6 7 8
multiset2 = 1 2 3 4
// STRING MULTISET EXAMPLE
// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 取两个multisets
multiset<string> multiset1{ "Geeksforgeeks" };
multiset<string> multiset2{ "Computer science", "Portal" };
// 交换multisets的元素
multiset1.swap(multiset2);
// 输出第一个multiset
cout << "multiset1 = ";
for (auto it = multiset1.begin();
it != multiset1.end(); ++it)
cout << ' ' << *it;
// 输出第二个multiset
cout << endl
<< "multiset2 = ";
for (auto it = multiset2.begin();
it != multiset2.end(); ++it)
cout << ' ' << *it;
return 0;
}
输出:
multiset1 = Computer science Portal
multiset2 = Geeksforgeeks
// CHARACTER MULTISET EXAMPLE
// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 取两个multisets
multiset<char> multiset1{ 'A', 'B', 'C' };
multiset<char> multiset2{ 'G', 'H', 'I' };
// 交换multisets的元素
multiset1.swap(multiset2);
// 输出第一个multiset
cout << "multiset1 = ";
for (auto it = multiset1.begin();
it != multiset1.end(); ++it)
cout << ' ' << *it;
// 输出第二个multiset
cout << endl
<< "multiset2 = ";
for (auto it = multiset2.begin();
it != multiset2.end(); ++it)
cout << ' ' << *it;
re```
输出:
multiset1 = G H I
multiset2 = A B C
时间复杂度: 常数