从STL中的list删除元素

C++ STL中删除list中的元素 阅读详情

申明,本文非笔者原创,原文转载自:http://www.cppblog.com/bujiwu/archive/2014/04/24/90087.html


正确版本:

 1 #include <iostream>
 2 #include <list>
 3 #include <algorithm>
 4 using namespace  std;
 5 
 6 int main(int argc, char* argv[])
 7 {
 8     list<int> MyList;
 9     
10     for (int i = 0; i < 10; i++)
11     {
12         MyList.push_back(i);
13     }
14 
15     list<int>::iterator Itor;
16 
17     for ( Itor = MyList.begin(); Itor != MyList.end(); )
18     {
19         if ( *Itor == 4 )
20         {
21             Itor = MyList.erase(Itor);
22         }
23         else
24         {
25             Itor++;
26         }
27     }
28 
29     copy(MyList.begin(), MyList.end(), ostream_iterator<int>(cout, " ") );
30     cout<<endl;
31 
32     return 0;
33 }

错误版本:
 1 #include <iostream>
 2 #include <list>
 3 #include <algorithm>
 4 using namespace  std;
 5 
 6 int main(int argc, char* argv[])
 7 {
 8     list<int> MyList;
 9     
10     for (int i = 0; i < 10; i++)
11     {
12         MyList.push_back(i);
13     }
14 
15     list<int>::iterator Itor;
16 
17     for ( Itor = MyList.begin(); Itor != MyList.end(); Itor++)
18     {
19         if ( *Itor == 4 )
20         {
21             MyList.erase(Itor); //断链,出错地方
22         }
23     }
24 
25     copy(MyList.begin(), MyList.end(), ostream_iterator<int>(cout, " ") );
26     cout<<endl;
27 
28     return 0;
29 }


【C++STL基础入门】list的增、删 在C++中,STL(Standard Template Library)是一个功能强大且常用的程序库,它为我们提供了许多容器和算法,使得编写高效且可维护的代码变得更加容易。其中,list是STL中的一个双向链表容器,它可以在任意位置高效地插入和删除元素。本文将介绍list容器的基本用法,包括如何增加和删除其中的元素。功能:将元素 val 插入到list容器的开头。参数:val - 要插入的元素的值。返回值:无返回值。// 输出:5 10return 0; 阅读详情

相关推荐

全网最全vue2技术栈实现AI问答机器人功能(流式与非流式两种接口方法)

markdown-it | markdown-it 中文文档上面的是 markdown-it 中文文档链接 ,供参考使用核心的东西就这些啦,如果有其他想问的,评论区留言即可~博客写作不易,希望大家多多支持,多多捧场~~~最后给大家分享一下 typed.js 网址,网上比较多,我觉得这个比较好理解一些Typed.js - Type your heart out (mattboldt.github.io)[这里是图片011]https://mattboldt.github.io/typed.js/

m0_74825108的博客 3057

C++之list删除元素

C++之list删除元素 对容器list存储的元素执行删除操作的时候,一般都是使用其成员函数实现的: (1)clear():删除list容器中的所有元素 (2)remove(value):删除容器中所有为value的元素 (3)remove_if():删除容器中满足条件的元素 (4)unique():删除容器中相邻的重复元素,只留下一个 (5)erase():删除 list...

乾坤我做主的博客 1万+

路由 NAT(简介、静态NAT、动态NAT、NATServer、NAPT、Easy-ip、NAT地址映射表)

为了有效节约公网IPv4地址,并提供一定的网络安全保障能力,NAT网络地址转换技术孕育而生。NAT(Network Address Translation)网络地址转换,主要将私有地址转换成公网地址。NAT优点能够缓解公网地址紧缺问题。解决IP地址空间冲突或重叠的问题。网络扩展性更高,本地控制也更容易。内网结构变得不可见,从而增加了安全性。NAT缺点因为地址映射的原因,当网络转换过多时会存在转发延迟的问题。端到端寻址变得困难,因为经过了NAT地址转换相当于换了张脸,想找人就难了。

Hades_Ling的优快云博客 8751

STL删除list元素

list.push_back(2); mylist.push_back(3); mylist.push_back(1); mylist.push_back(2);    // 删除元素2    // 方式一    mylist.remove(2);    // 方式二    mylist.erase(remove_if(mylist.b

Posix 的专栏 616

CUDA编译踩坑实录:如何正确设置-gencode参数适配你的GPU算力

本文深入解析CUDA编译中-gencode参数的核心原理与实战配置,帮助开发者解决常见的'Unsupported gpu architecture'错误。通过厘清虚拟架构与真实架构的区别,并提供多版本兼容的CMake配置方案,确保编译出的代码能精准适配不同GPU算力,兼顾性能与广泛兼容性。

weixin_28829903的博客 338

卫星通信链路预算实战:从EIRP到Eb/N0的完整计算指南(含Excel模板)

本文提供了一份卫星通信链路预算的实战指南,详细解析了从EIRP到Eb/N0的完整计算流程。文章重点对比了C波段与Ku波段在应对降雨衰减等动态因素时的不同策略,并分享了包含核心公式的Excel模板,帮助工程师将理论转化为可执行的系统设计依据。

weixin_29230773的博客 534

【C++】STL 容器 - list 双向链表容器 ③ ( list 常用 api 简介 | 中间位置 插入 / 删除 元素 | insert 函数 | clear 函数 | erase 函数 )

一、list 双向链表容器 的 中间位置 插入 元素 1、在指定位置插入 1 个元素 - insert 函数 2、在指定位置插入 n 个相同元素 - insert 函数 3、中间位置 插入 另一个容器的指定范围内的 元素 - insert 函数 二、list 双向链表容器 的 中间位置 删除 元素 1、删除容器中所有元素 - clear 函数 2、删除容器中指定元素 - remove 函数 3、删除容器中指定 迭代器位置 的元素 - erase 函数 4、删除容器中指定 迭代器范围 的元素 - erase

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

汽车软件工程师必看:ASPICE开发流程全解析(附各阶段交付物清单)

本文全面解析了汽车行业广泛采用的ASPICE开发流程,详细介绍了从需求挖掘到系统架构设计、软件工程及测试验证各阶段的关键操作和交付物清单。针对汽车软件工程师,提供了实用的协作指南和工具推荐,帮助团队提升开发效率并降低项目风险,是掌握ASPICE标准的必备指南。

weixin_30733003的博客 642

STL 中list删除元素

list容器中删除元素分如下两种情形,第一种是很大条地使用remove函数输入list的头部iterator和尾部iterator,如下代码 list ilist; ilist.push_back(1); ilist.push_back(2); remove(ilist.begin(),ilist.end(),1);//删除整个list中值为1的字节点 上面这个程序不需要用户参与,属于比

honpey爱编程 3015

海康VisionMaster与西门子Smart 200进行S7通信

海康VisionMaster与西门子Smart 200进行S7通信

haier123888的博客 8178

LeRobot X-VLA:首个适用于任意机器人、任意任务的软提示机器人基础模型

X-VLA是一种基于软提示的视觉-语言-动作模型,通过可学习嵌入向量编码不同机器人配置,实现跨平台统一控制。该框架采用两阶段训练:先在29万次多平台任务中学习通用策略,再通过微调少量参数(仅1%)适配新机器人。实验表明,0.9B参数的X-VLA在6个仿真和3个真实平台上表现优异,如LIBERO任务达93%成功率,布料折叠任务100%完成。其核心创新是将硬件差异视为"任务",用软提示引导Transformer处理异构数据,为机器人基础模型提供可扩展方案。

2506_90492529的博客 1241

stl list 删除元素_删除所有出现的元素,并从列表中删除一些特定的元素。 C ++ STL...

stl list 删除元素 list.remove()和list.remove_if()函数 (list.remove() and list.remove_if() functions) remove() function is used to remove all occurrences of a given element from the list and function remove_i...

cumudi0723的博客 789

YOLOv8融合改进 更换检测头为Detect_DyHead同时添加C2f_DBB模块

yolov8独家训练测试融合网络结构,提供详细步骤详细代码,手把手教你在yolov8官方包中把检测头更换为Detect_DyHead检测头,并且将原始的C2f模块更换成C2f_DBB模块,提高检测精度,亲测在多个数据集上有涨点!!!!!

分享一些自己改进代码的实例 4747

STL list如何删除指定的元素

<br />在网上找资料的时候看到一种删除list中元素的方法,如下<br />std::list<Subscriber*> subscribers_;<br />subscribers_.erase(std::remove(subscribers_.begin(),subscribers_.end(), &subscriber),<br />          subscribers_.end());<br /> <br />其实对于list,完全可以用list::remove函数直接移除元素,效果是一

sunmanzth的专栏 8812

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

删除STL list容器中元素使用经验分享

    最近在做项目时,用到了STL list容器。在使用中,需要用到list容器的erase方法删除满足条件的对象。    描述如下:        List容器中存放对象指针,假设为Student对象指针。故list容器描表示为std::list,我们再假设此容器中已经有了很多个元素了。接下来我们要做的是遍历容器,删除其中满足某种条件的Student对象指针元素。假设删除性别为男的St

soulforcemw的专栏 1898

VC中sqlite的使用

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

php list删除元素,C++ STL list删除元素详解

对 list 容器存储的元素执行删除操作,需要借助该容器模板类提供的成员函数。幸运的是,相比其它 STL 容器模板类,list 模板类提供了更多用来实现此操作的成员函数(如表 1 所示)。表 1 实现 list 容器删除元素的成员函数成员函数功能pop_front()删除位于 list 容器头部的一个元素。pop_back()删除位于 list 容器尾部的一个元素。erase()该成员函数既可以删...

weixin_31688167的博客 491

深度学习工具包 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中对包含对象的 list 进行排序以及删除其中的元素

C++ STL中对包含对象的 list 进行排序以及删除其中的元素

qq_41317716的博客 724

STL List和Deque在删除元素时的区别

在STL容器的操作中,往往需要遍历删除某些元素,本文将给出如何遍历删除元素的快速方法。同时说明List和Deque删除元素的区别。 至于List和Deque,甚至Vector的区别,读者自行去了解,网上很多解释。这里只说明迭代器的区别,让大家快速正确的使用STL容器。 List在Erase后,迭代器仍然可以使用;Deque在Erase后,队列结果发生了变化,迭代器将与之不兼容,执行会报错。STL容

sdft06的博客 1518

对C++ STL,list元素的循环删除操作

在用iterator遍历整个list时,iterator相当于链表中的当前结点指针,如果我们在循环体中遍历整个list, 并且对满足一定条件的元素进行删除操作,一定要先保存当前要删除结点的下一个结点的iterator,否则删除完元素的下一次循环体会因为指针丢失而报错。我们看一看以下程序:#include "stdafx.h"#include using namespace std;int

路佳的专栏 9035

stl的vector,map,list删除元素

vector看成数组,list看成链表,具体的内部存储方法可以参考stl 数据定义 #include #include #include using namespace std; typedef map ByteMap; ByteMap testMap; typedef vector IntVec; IntVec testVec; typedef

长歌行 1388

对C++ STL,list元素的循环删除操作 //断链,出错地方

1 #include iostream>  2 #include list>  3 #include algorithm>  4 using namespace  std;  5   6 int main(int argc, char* argv[])  7 {  8     listint> MyList;  9      10     for (int i = 0; i  1

human_cn的专栏 724

C++/STL用erase删除元素(vector,deque),(list,set,map)

STL中的容器按存储方式分为两类,一类是按以数组形式存储的容器(如:vector 、deque);另一类是以不连续的节点形式存储的容器(如:list、set、map)。在使用erase方法来删除元素时,需要注意一些问题。       在使用 list、set 或 map遍历删除某些元素时可以这样使用: 正确使用方法1      std::list List;       std:

迎难而上 4871

【C++】STL 容器 - list 双向链表容器 ② ( list 常用 api 简介 | 首尾 添加 / 删除 元素 | 获取首尾元素 | 正向迭代与反向迭代 )

一、元素操作 1、首尾 添加 / 删除 元素 2、获取 首尾 元素 二、迭代器遍历容器 1、正向迭代与反向迭代 2、代码示例

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

STL--list如何实现元素的插入和删除

list如何实现元素的插入和删除

学无止境 1269

STL链表之删除指定元素(list)

链表-删除指定元素 Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^ 题目描述        对于一个给定的线性表,要求删除线性表内的大于等于 min 且小于等于 max 的数,并输出删除后的线性表 要求:必须使用链表做,否则不计成绩! 输入         输入的第一行为一个正整数 T,表示有 T 组测试数

Orz~~Orz 3336
上一篇: 视频浓缩摘要简介
下一篇: stl容器的区别:vector list deque set map-底层实现
ChenLee_1
博客等级 码龄17年 6199粉丝 179原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值