18.8.3 set大小和交换
函数原型:
size();
//返回容器中元素的个数empty();
//判断容器是否为空swap(st);
//将本身与st交换
1、大小操作
#include <iostream>
#include <set>
#include <sstream>
using namespace std;
template<class T>
void printSet(const set<T>& s)
{
for (set<T>::const_iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << '\t';
}
cout << endl;
}
//大小
void test1()
{
set<int>s1;
//插入只有insert
s1.insert(10);
s1.insert(40);
s1.insert(30);
s1.insert(20);
printSet(s1);
//判断是否为空
if (s1.empty())
{
cout << "s1为空" << endl;
}
else
{
cout << "s1不为空" << endl;
cout << "s1的大小为:" << s1.size() << endl;
}
}
int main()
{
test1();
}
2、交换操作
#include <iostream>
#include <set>
#include <sstream>
using namespace std;
template<class T>
void printSet(const set<T>& s)
{
for (set<T>::const_iterator it = s.begin(); it != s.end(); it++)
{
cout << *it << '\t';
}
cout << endl;
}
//交换
void test2()
{
set<int>s1;
s1.insert(10);
s1.insert(40);
s1.insert(30);
s1.insert(20);
set<int>s2;
s2.insert(100);
s2.insert(400);
s2.insert(300);
s2.insert(200);
cout << "交换前:" << endl;
printSet(s1);
printSet(s2);
cout << "交换后:" << endl;
s1.swap(s2);
printSet(s1);
printSet(s2);
}
int main()
{
test2();
}