源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C++ STL入门教程(6) set(集合)的使用方法

  • 时间:2020-05-24 22:56 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C++ STL入门教程(6) set(集合)的使用方法
[b]一、简介[/b] 集合(Set)是一种包含已排序对象的关联容器,不允许有重复元素。 [img]http://files.jb51.net/file_images/article/201708/2017818171702188.jpg?2017718171816[/img] [b]二、完整程序代码[/b]
/*请务必运行以下程序后对照阅读*/ 
 
#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(); 
} 

[b]三、补充 [/b] map容器是键-值对的集合,好比以人名为键的地址和电话号码。相反地,set容器只是单纯的键的集合。当我们想知道某位用户是否存在时,使用set容器是最合适的。 参考网址:[url=http://www.cplusplus.com/reference/set/set/]http://www.cplusplus.com/reference/set/set/[/url] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部