STLset容器大小和交换

STLset容器大小和交换

功能描述:
统计set容器大小以及交换set容器
函数原型:

size();        //返回容器中元素的数目
empty();      //判断容器是否为空
swap(st);     //交换两个集合容器

代码示例:

#include<iostream>
#include<set>
using namespace std;
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(30);
       s1.insert(40);
       //打印容器
       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(30);
       s1.insert(40);
       set<int>s2;
       //插入数据
       s2.insert(100);
       s2.insert(200);
       s2.insert(300);
       s2.insert(400);
       cout << "交换前:" << endl;
       printSet(s1);
       printSet(s2);
       cout << "交换后:" << endl;
       s1.swap(s2);
       printSet(s1);
       printSet(s2);
}
int main()
{
   
       test01();
       test02();
       return 0;
}

总结:

统计大小—size
判断是否为空—empty
交换容器—swap

数据结构与算法 文章被收录于专栏

本专栏收录数据结构与算法知识点

全部评论

相关推荐

迷茫的大四🐶:你这个拿去投央国企吧,投私企包过不了的
点赞 评论 收藏
分享
10-28 10:48
已编辑
门头沟学院 Java
孩子我想要offer:发笔试后还没笔试把我挂了,然后邮箱一直让我测评没测,后面不知道干嘛又给我捞起来下轮笔试,做完测评笔试又挂了😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务