📅  最后修改于: 2020-10-19 07:55:40             🧑  作者: Mango
C++ Multiset swap()函数用于交换(或交换)两个multiset容器的内容,但两个multiset容器的类型必须相同,尽管大小可能有所不同。
void swap (multiset& x);
x:用于交换内容的multiset容器。
没有
不变。
引用两个multiset容器的元素的所有引用,迭代器和指针都保持有效,但是现在引用另一个multiset容器中的元素,并对其进行迭代。
容器和x均被修改。
如果抛出异常,则对容器没有影响。
让我们看一个简单的示例,将一个multiset容器的元素交换为另一个:
#include
#include
using namespace std;
int main(void) {
multiset m1 = {1,2,3,4,5,3};
multiset m2;
m2.swap(m1);
cout << "Multiset m2 contains following elements" << endl;
for (auto it = m2.begin(); it != m2.end(); ++it)
cout << *it<< endl;
return 0;
}
输出:
Multiset m2 contains following elements
1
2
3
3
4
5
在上面的示例中,multiset容器m1具有五个元素,而m2为空。当您将m1交换为m2时,m1的所有元素都将交换为m2。
让我们看一个简单的示例来交换两个multiset容器的内容:
#include
#include
using namespace std;
int main ()
{
int myints[]={19,72,4,36,20,20};
multiset first (myints,myints+3); // 4,19,72
multiset second (myints+3,myints+6); // 20,20,36
first.swap(second);
cout << "first contains:";
for (multiset::iterator it=first.begin(); it!=first.end(); ++it)
cout << ' ' << *it;
cout << '\n';
cout << "second contains:";
for (multiset::iterator it=second.begin(); it!=second.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
输出:
first contains: 20 20 36
second contains: 4 19 72
让我们看一个简单的示例,以交换两个multiset容器的内容:
#include
#include
using namespace std;
int main()
{
// Take any two multisets
multiset multiset1, multiset2;
multiset1 = {'a','b','c','d','c'};
multiset2 = {'x','y','z','y'};
// Swap elements of multisets
swap(multiset1, multiset2);
// Print the elements of multisets
cout << "multiset1:\n";
for (auto it = multiset1.begin(); it != multiset1.end(); it++)
cout << "\t" << *it<< '\n';
cout << "multiset2:\n";
for (auto it = multiset2.begin(); it != multiset2.end(); it++)
cout << "\t" << *it<< '\n';
return 0;
}
输出:
multiset1:
x
y
y
z
multiset2:
a
b
c
c
d
在上面的示例中,另一种形式的swap()函数用于交换两个multiset容器内容。
让我们看一个简单的例子:
#include
#include
int main( )
{
using namespace std;
multiset s1, s2, s3;
multiset ::iterator s1_Iter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 10 );
s2.insert( 100 );
s2.insert( 200 );
s3.insert( 200 );
cout << "The original multiset 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, multiset 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, multiset s1 is:";
for ( s1_Iter = s1.begin( ); s1_Iter != s1.end( ); s1_Iter++ )
cout << " " << *s1_Iter;
cout << "." << endl;
}
输出:
The original multiset s1 is: 10 10 20.
After swapping with s2, multiset s1 is: 100 200.
After swapping with s3, multiset s1 is: 200.