C++set容器-大小和交換
阿新 • • 發佈:2021-02-19
set大小和交換
功能描述:
統計set容器大小以及交換set容器
函式原型:
程式碼如下:
#include <iostream>
using namespace std;
#include <set>
//set容器 大小和容器
void printSet(set<int > &s) {
for (set<int >::iterator it = s.begin(); it != s.end(); it++) {
cout << *it << " " ;
}
cout << endl;
}
//大小
void test01() {
set<int >s1;
//插入
s1.insert(10);
s1.insert(20);
s1.insert(40);
s1.insert(30);
//列印
printSet(s1);
//判斷是否為空
if (s1.empty()) {
cout << "s1為空" << endl;
} else {
cout << "s1不為空" << endl;
cout << "s1的大小為:" << s1.size() << endl;
}
}
//交換
void test02() {
set<int >s1;
s1.insert(10);
s1.insert(20);
s1.insert(40);
s1.insert(30);
set<int>s2;
s2.insert(100);
s2.insert(200);
s2.insert(400);
s2.insert(300);
cout << "交換前:" << endl;
printSet(s1);
printSet(s2);
cout << "交換後:" << endl;
s1.swap(s2);
printSet(s1);
printSet(s2);
}
int main() {
test01();
cout << "----------------------------" << endl;
test02();
return 0;
}