设置:在C++ STL中:SWAP-()

设置 是一种关联容器,其中每个元素必须是唯一的,因为元素的值标识它。元素的值一旦添加到集合中就不能修改,尽管可以删除并添加该元素的修改值。

null

set::swap() 此函数用于交换两个集合的内容,但集合必须为 同一类型 ,尽管尺寸可能不同。

语法:

set1.swap(set2)

返回值: 没有

例如:

Input  : set1 = {1, 2, 3, 4}
         set2 = {5, 6, 7, 8}
         set1.swap(set2);
Output : set1 = {5, 6, 7, 8}
         set2 = {1, 2, 3, 4}

Input  : set1 = {'a', 'b', 'c', 'd'}
         set2 = {'w', 'x', 'y', 'z'}
         set1.swap(set2);
Output : set1 = {'w', 'x', 'y', 'z'}
         set2 = {'a', 'b', 'c', 'd'}

// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Take any two sets
set< int > set1{ 1, 2, 3, 4 };
set< int > set2{ 5, 6, 7, 8 };
// Swap elements of sets
set1.swap(set2);
// Print the first set
cout << "set1 = " ;
for ( auto it = set1.begin();
it != set1.end(); ++it)
cout << ' ' << *it;
// Print the second set
cout << endl
<< "set2 = " ;
for ( auto it = set2.begin();
it != set2.end(); ++it)
cout << ' ' << *it;
return 0;
}


输出:

set1 =  5 6 7 8
set2 =  1 2 3 4

时间复杂性: 常数

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享