c++ STL set集合中包含的函数及其应用(一)

C++ STL 集合set 本文主要简述集合的原理和实现,便于快速学习和查阅。 集合的原理 set集合容器实现了红黑树(Red-Black Tree)的平衡二叉检索树的数据结构,在插入元素时,它会自动调整二叉树的排列,把该元素放到适当的位置,以确保每个子树根节点的键值大于左子树所有节点的键值,而小于右子树所有节点的键值。 另外,还得确保根节点左子树的高度与右子树的高度相等,这样,二叉树的高度最小,从而检索速度最快。 ... 阅读详情
  1. set简介:
    set是STL中一种标准关联容器,它底层使用平衡的搜索树——红黑树实现,插入删除操作时仅仅需要指针操作节点即可完成,不涉及到内存移动和拷贝,所以效率比较高。在set中元素都是唯一的,而且默认情况下会对元素自动进行升序排列,支持集合的交(set_intersection),差(set_difference) 并(set_union),对称差(set_symmetric_difference) 等一些集合上的操作,如果需要集合中的元素允许重复那么可以使用multiset元素。

  2. set常用函数
    (1)三种形成集合的方法:

#include<iostream>
#include<set>
using namespace std;
void print(multiset<int>& s){
    multiset<int>::iterator it=s.begin();
    while(it!=s.end()){cout<<*it<<" ";it++;}
    cout<<endl;
} 
int main(){
    int a[]={5,3,9,3,7,2,9,3};
    multiset<int>s1;
    //通过构造函数insert()添加集合。 
    for(int i=0;i<sizeof(a)/sizeof(int);i++)s1.insert(a[i]);
    print(s1);
    //通过复制构造函数set(const set& x)创建集合 
    multiset<int>s2(s1);print(s2);
    //通过构造函数set(conset value_type*first,const value_type* last)创建集合
    multiset<int>s3(a,a+sizeof(a)/sizeof(int));print(s3); 
}

输出展示:
这里写图片描述
(2)set常用的函数:

(话不多说直接上代码)

#include<iostream>
#include<set>
using namespace std;
void print(set<int>&s){
    set<int>::iterator it=s.begin();
    while(it!=s.end()){cout<<*it<<" ";it++;}
    cout<<endl;
}
int main(){
    int a[]={3,2,9,4,5};
    set<int>s(a,a+sizeof(a)/sizeof(int));
    //反向遍历 
    set<int>::reverse_iterator it=s.rbegin();
    while(it!=s.rend()){cout<<*it<<" ";it++;}cout<<endl; 
    //判断集合是否为空
    if(s.empty())puts("集合为空");else puts("集合不为空");
    //计算集合的大小
    cout<<s.size()<<endl;
    //一个集合中x值出现的次数
    cout<<s.count(2)<<endl;
    //元素检索
    set<int>::iterator te=s.find(5);
    if(te==s.end())puts("没找到");
    else puts("找到了");
    set<int>::iterator iii=s.lower_bound(3);
    cout<<*iii<<endl;
    set<int>::iterator ttt=s.upper_bound(2);
    cout<<*ttt<<endl;
    //删除元素
    set<int>::iterator itt=s.find(2);
    s.erase(itt); print(s);//删除迭代指针itt处的元素
    s.erase(5);print(s);//删除元素值等于key的元素.

} 

(3)equal_range,pair,count,size用法举例:

#include<iostream>
#include<set>
using namespace std;
int main(){
    int a[]={5,3,9,3,7,2,9,3};
    set<int>myset(a,a+sizeof(a)/sizeof(int));
    multiset<int>mymultiset(a,a+sizeof(a)/sizeof(int));

    pair<set<int>::iterator,set<int>::iterator>s1;
    pair<multiset<int>::iterator,multiset<int>::iterator>s2;

    s1=myset.equal_range(3);
    s2=mymultiset.equal_range(3);

    int ncount=myset.count(3);
    int nMulticount=mymultiset.count(3);

    set<int>::iterator te;
    cout<<"set(搜索值等于3的元素):"<<endl;
    for(te=s1.first;te!=s1.second;te++)cout<<*te<<" ";cout<<endl;
    cout<<"个数是:"<<ncount<<endl;
    cout<<"总个数是:"<<myset.size()<<endl;

    multiset<int>::iterator it;
    cout<<"multiset(搜索值等于3的元素):"<<endl;
    for(it=s2.first;it!=s2.second;it++)cout<<*it<<" ";cout<<endl;
    cout<<"个数是:"<<nMulticount<<endl;
    cout<<"总个数是:"<<mymultiset.size()<<endl;
}

结果展示:
这里写图片描述
未完待续……..

STL-set集合 阅读详情

相关推荐

C++ STL 集合运算

C++ STL 集合运算 定义于头文件&lt;algorithm&gt;的算法: 集合运算的前提是两个集合必须按照同样的规则排序就绪,否则不能进行集合运算! - map,set是有序集合,可以直接参加运算;vector是无序集合,参与运算前必须首先排序. template&lt; class InputIt1, class InputIt2, class OutputIt &gt;...

weixin_42993054的博客 5656

C++中set用法详解

1.关于set C++ STL 之所以得到广泛的赞誉,也被很多人使用,不只是提供了像vector, string, list等方便的容器,更重要的是STL封装了许多复杂的数据结构算法和大量常用数据结构操作。vector封装数组,list封装了链表,map和set封装了二叉树等,在封装这些数据结构的时候,STL按照程序员的使用习惯,以成员函数方式提供的常用操作,如:插入、排序、删除、查找等。让用户在STL使用过程中,并不会感到陌生。 关于set,必须说明的是set关联式容器。set作为一个容器也是用来存储同一

sh13661847134的博客 2775

【C++21天养成计划】集合——快速上手STL set (multiset) 类(Day16)

小白专属的《C++21天养成计划》,快速入门C++高效教程!

不积跬步,无以至千里! 4363

如何检查元素是否在std :: set中?

How do you check that an element is in a set? 你如何检查元素是否在集合中? Is there a simpler equivalent of the

CHCH998的博客 2477

C#与Vector XL驱动库实战:CAN通道配置与端口访问详解

本文详细解析了使用C#调用Vector XL驱动库进行CAN总线通信开发的核心步骤。重点阐述了如何通过XL_GetDriverConfig获取硬件通道信息,并厘清channelMask与accessMask的区别与转换关系,最终指导开发者正确使用XL_OpenPort函数配置并打开CAN端口,为构建稳定的汽车电子测试与诊断应用奠定基础。

weixin_28452161的博客 362

arduino uno spi驱动12864

arduino uno spi驱动12864

yvee的博客 2060

C++ 集合中查找元素

#include <iostream> #include <set> using namespace std; int main() { set<char> cSet; //利用set对象创建字符类型的集合 cSet.insert('B'); //插入元素 cSet.insert('C'); cSet.insert('D'); cSet.insert('A'); cSet.insert('F'); cout << "old set:" &.

dxm809的博客 2834

交换机基本介绍(分类、性能指标、硬件构成及工作方式)

一、交换机的分类与性能指标 1.1交换机的分类 按照网络构成方式来分的话,交换机分为三类:接入层交换机、汇聚层交换机和核心层交换机。 按照OSI模型来划分的话,分为:二层交换机、三层交换机和四层交换机 还有一种按照硬件形态来划分,可以分成两类:盒式交换机和机框式交换机。 盒式交换机是一种有固定端口数,有时也会带有少量扩展槽的交换机。机架式交换机是一种插槽式的交换机,这种交换机扩展性较好,可支持不同的网络类型,可支持更大端口密度的网络。一般在数据中心的接入层都会采用盒式交换机,盒式...

monologuezjp的博客 4万+

C++中集合set的常用操作

介绍C++ 集合set的基本操作。

suiyueruge2019的博客 2302

手把手教你用Zynq-7100 FPGA实现100Mbps OOK信号定时同步(含完整Verilog代码)

本文详细介绍了如何在Zynq-7100 FPGA平台上实现100Mbps OOK信号的定时同步,涵盖插值算法、Gardner定时误差检测等关键技术。通过完整的Verilog代码和优化技巧,解决了50MHz外部时钟条件下的400MHz采样率同步挑战,为无线通信系统设计提供实用解决方案。

weixin_42522374的博客 301

机器人控制算法九之 位姿描述与空间变换

机器人控制算法九之 位姿描述与空间变换

yohnyang的博客 1032

C++ STL-Set的用法

最后输出为count()函数是C++ STL中的内置函数,它。由于set容器仅包含唯一元素,因此。最后输出结果为输出结果为。

2303_77598765的博客 534

【Bug已解决】npm install -g @anthropic-ai/claude-code 出现 EACCES: permission denied 解决方案

方案适用场景推荐指数nvm 管理 Node长期开发环境,一次配置永久生效⭐⭐⭐⭐⭐修改 npm 全局目录不想引入 nvm,快速解决⭐⭐⭐⭐修复现有目录权限之前用过 sudo 装包,需要修复⭐⭐⭐Windows 管理员/改目录Windows 平台专用⭐⭐⭐⭐官方原生安装脚本想彻底避开 npm 权限问题⭐⭐⭐⭐报的本质是npm 全局安装目录的属主权限与当前执行用户不匹配,而不是 npm 或 Claude Code 本身有问题。不要用sudo"强行"解决。

一键难忘的博客 1万+

【C++】STL - 集合 set

集合(set)是一个内部自动有序且不含重复元素的容器,它可以在需要删除重复元素的情况下大放异彩,节省时间,减少思维量。set 就是关键字的简单集合,当只是想知道一个值是否存在时,set 是最有用的。set 内部采用的是一种非常高效的平衡检索二叉树:红黑树(Red-Black Tree),也称为 RB 树,RB 树的统计性能要好于一般平衡二叉树。在 set 中每个元素的值都唯一,而且系统能根据元素的值自动进行排序,set 中元素的值不能直接被改变。

weixin_53235104的博客 2万+

OpenHarmony 显示Display驱动全栈解析:DisplayLayer + Gralloc + Gfx 三位一体,打造高性能图形底座

OpenHarmony Display显示驱动模块是系统图形渲染和显示功能的基础组件,负责管理显示设备、图层渲染、内存分配等核心功能。该模块采用HDI(Hardware Driver Interface)设计架构,为上层图形服务提供统一的显示能力接口,实现了显示设备的初始化、图层管理、内存分配与映射、硬件加速等关键功能。DisplayLayer:负责显示图层的管理, 包括图层创建、显示属性设置、图层填充及刷新等操作;

m0_67505153的博客 315

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

c++ STL 之集合—— set 详解

set是 stl 的一个关联容器,名叫“集合”,何为“集合”?其实就是一个数组,但有了数组何必还需集合?

zhhg0123的博客 2886

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

C++集合set的用法

众所周知STL是C++中十分实用的容器,set便是其中之一。最近做的题都接触到了set(集合),正好学习了一下,将自己的成果写一写。没有接触过的人也可以看看,表示set非常的好用。 (话说最近好久都没有写过博客了) 定义 首先我们需要一个头文件来使用set #include <set> set的定义类似vector(动态数组): set<int> S1;//定义了一个in...

C20200521的博客 3263

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

【C++】STL 容器 - set 集合容器 ⑦ ( 查找元素 - set#find 函数 | 获取元素个数 - set#count 函数 )

一、查找元素 - set#find 函数 1、函数原型 简介 2、代码示例 - set#find 函数 二、获取元素个数 - set#count 函数 1、函数原型 简介 2、代码示例 - set#find 函数

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 7176

【c++丨STL】set/multiset的使用

set(集合)和multiset(多重集合)是STL中的容器,分别用于处理唯一元素和允许重复元素的场景,它们的底层结构都是红黑树(一种自平衡二叉搜索树)。set和multiset有以下共同特点:1. 容器元素自动按照升序排列(也可通过传入第二个模板参数调整排序规则)。2. 元素插入、删除、查找的时间复杂度均为O(logN)。set和multiset的核心区别是:set不允许容器内有重复元素,能够达到去重的效果;而multiset支持插入重复元素。鉴于set和multiset的接口功能。

2301_80955819的博客 2119

C++ 集合set 详解

1.关于set C++ STL 之所以得到广泛的赞誉,也被很多人使用,不只是提供了像vector, string, list等方便的容器,更重要的是STL封装了许多复杂的数据结构算法和大量常用数据结构操作。vector封装数组,list封装了链表,map和set封装了二叉树等,在封装这些数据结构的时候,STL按照程序员的使用习惯,以成员函数方式提供的常用操作,如:插入、排序、删除、查找等。让

qq_39450326的博客 3万+

C ++ STL中的set :: find()函数

C ++ STL set :: find()函数 (C++ STL set::find() function) set::find() function is a predefined function, it is used to check whether an element belong to the set or not, if element finds in the set con...

cumubi7552的博客 1万+

C++集合 STL集合 set集和--交集、并集、差集、对称差

STL库中有丰富的集合运算方法,我们可以使用它们快速完成交集、并集、差集、对称差集的运算。(转载请指明出于breaksoftware的csdn博客) 交集(intersection) 交集是集合运算中经常会用到的计算,其表达是两个集合共有的部分(图中红色区域) STL中有set_intersection方法可以实现该功能。它是C++17开始支持的方法,声明于<algorithm>中。其中一种形式是 template< class Executi...

xiaozhidian的博客 8624

【C++ STL哈希容器】unordered_set 无序集合

【C++ STL有序关联容器】set 集合。查看已定义 uset 容器存储元素的个数,并通过正向迭代器输出各元素。int main()//创建一个空的unordered_set容器//给 uset 容器添加数据//查看当前 uset 容器存储元素的个数//遍历输出 uset 容器存储的所有元素iter!

普罗米修斯的博客 1477

【C++】STL 容器 - set 集合容器 ① ( set 集合容器简介 | set 集合容器操作的时间复杂度 | set 集合容器常用操作 )

一、set 集合容器 1、set 集合容器简介 2、set 集合容器操作的时间复杂度 3、set 集合容器常用操作 二、代码示例 - set 集合容器 1、代码示例 2、执行结果

让 学习 成为一种 习惯 ( 韩曙亮 の 技术博客 ) 2850

C++ STL set集合的使用

一些涉及到集合的算法题目,可以考虑使用STL里的set来很方便地解决问题。

青春无问西东 岁月自成芳华 1万+
上一篇: Codeforces Round #502 (in memory of Leopoldo Taravilse, Div. 1 + Div. 2) C. The Phone Number
下一篇: poj 3061 Subsequence(二分法)
图南1204
博客等级 码龄9年 21粉丝 118原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值