温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中set集合怎么用

发布时间:2021-08-09 13:58:11 来源:亿速云 阅读:156 作者:小新 栏目:编程语言

这篇文章主要为大家展示了“C++中set集合怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“C++中set集合怎么用”这篇文章吧。

一、简介

集合(Set)是一种包含已排序对象的关联容器,不允许有重复元素。

C++中set集合怎么用

二、完整程序代码

/*请务必运行以下程序后对照阅读*/ 
 
#include <set> 
#include <iostream> 
using namespace std; 
 
int main() 
{ 
  ///1. 初始化 
  set<int> num; 
  set<int>::iterator iter; 
  cout << num.max_size() << endl;///set容纳上限 
  cout << endl; 
 
  ///2. 添加元素 
  for (int i = 0; i < 10; i++) 
    num.insert(i); 
  cout << num.size() << endl; 
  cout << endl; 
 
  ///3. 遍历 
  ///不同于map,set容器不提供下标操作符 
  for (iter = num.begin(); iter != num.end(); iter++) 
    cout << *iter << " " ; 
  cout << endl; 
  cout << endl; 
 
  ///4. 查询 
  iter = num.find(1); 
  if (iter != num.end()) 
    cout << *iter << endl; 
  else 
    cout << -1 << endl; 
  iter = num.find(99); 
  if (iter != num.end()) 
    cout << *iter << endl; 
  else 
    cout << -1 << endl; 
  cout << endl; 
 
  ///5. 删除 
  iter = num.find(1); 
  num.erase(iter); 
  cout << num.size() << endl; 
  for (iter = num.begin(); iter != num.end(); iter++) 
    cout << *iter << " " ; 
  cout << endl; 
  cout << endl; 
 
  ///6. 判空与清空 
  if (!num.empty()) 
    num.clear(); 
}

三、补充

map容器是键-值对的集合,好比以人名为键的地址和电话号码。相反地,set容器只是单纯的键的集合。当我们想知道某位用户是否存在时,使用set容器是最合适的。

以上是“C++中set集合怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节
推荐阅读:
  1. Python集合set
  2. set集合

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI