服务器之家

服务器之家 > 正文

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

时间:2021-05-29 19:26     来源/作者:synapse7

一、简介

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

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

二、完整程序代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*请务必运行以下程序后对照阅读*/
 
#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容器是最合适的。

参考网址:http://www.cplusplus.com/reference/set/set/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/synapse7/article/details/10097645

标签:
Set C++ STL 

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部