std::map删除某个或者某些元素的示例

C++——std::Map 写在前面: 有一段时间没有继续进行C++容器的学习了。这次接着C++-std::Vector 的内容继续学习。通过之前的vector的学习,我发现虽然对该容器有一个比较全面的认识,但是很多细节还是不能注意好。比如在 LeetCode-406. Queue Reconstruction by Height 这道题中使用vector的insert函数,而我之前的方法由于没有把握好erase函数的使用... 阅读详情
#include <iostream>
#include <map>
#include <string>
using namespace std;

int main()
{
	typedef std::map<string, int> StringIntMap;
	StringIntMap coll;
	coll["aa"] = 1;
	coll["bb"] = 2;
	coll["cc"] = 1;
	coll["dd"] = 2;

	int value = 1;
	//for (StringIntMap::iterator pos = coll.begin(); pos != coll.end(); )
	//{
	//	if (pos->second == 1)
	//	{
	//		coll.erase(pos++);  //自从c++11之前的写法
	//	}
	//	else
	//	{
	//		++pos;
	//	}
	//}

	for (StringIntMap::iterator pos = coll.begin(); pos != coll.end(); )
	{
		if (pos->second == 1)
		{
			pos = coll.erase(pos); //自从c++11开始
		}
		else
		{
			++pos;
		}
	}

	for (StringIntMap::iterator pos = coll.begin(); pos != coll.end(); ++pos)
	{
		std::cout << "key:" << pos->first << " value:" << pos->second << std::endl;
	}

	getchar();
	return 0;
}
C++(10): std::map、std::multimap与std::unordered_map std::map、std::multimap 和 std::unordered_map 是 C++ 标准模板库(STL)中的三种关联容器,它们提供了存储键值对(pair)的方式,并允许通过键来快速检索值。这三者之间的主要区别在于它们的内部数据结构和对元素的排序方式。 阅读详情

相关推荐

三种容器 std::vector、std::map、std::unordered_set 的对比分析

选择合适的容器应根据具体需求,包括添加元素的频率、查找元素的方式和遍历容器的需求等。适用于需要频繁访问和添加元素的场景,std::map适用于需要有序存储和高效查找的场景,而则适用于需要快速查找且不关心元素顺序的场景。通过理解每种容器的特点和适用场景,可以编写更高效、更易维护的代码。

winrich的博客 1453

Stl map的高效删除

这种删除方式也是STL源码一书中推荐的方式,分析 mapStudent.erase(iter++)语句,map中在删除iter的时候,先将iter做缓存,然后执行iter++使之指向下一个结点,再进入erase函数体中执行删除操作,删除时使用的iter就是缓存下来的iter(也就是当前iter(做了加操作之后的iter)所指向结点的上一个结点)。需要注意的是,使用erase()函数删除元素时,要避免在循环中使用迭代器进行删除操作,因为这会导致迭代器失效,从而引发未定义的行为。1. 通过迭代器删除。

kupePoem的专栏 5371

用ST25DV芯片+KiCad快速设计NFC标签天线:参数计算/脚本生成/实测优化全流程

本文详细介绍了使用ST25DV芯片和KiCad工具设计NFC标签天线的全流程,包括参数计算、脚本生成和实测优化。通过解析芯片等效工作原理和设计思路,帮助开发者避开常见陷阱,实现高效、可量产的天线设计。文章还提供了Python计算工具和KiCad自动化脚本,大幅提升设计效率和成功率。

jj890的博客 758

map 删除指定元素

#include #include using namespace std; mapg_OnMic; int main() { for (int i = 0; i < 10;i++) { g_OnMic.insert(make_pair(i, i)); } map::iterator iter; for (iter = g_OnMic.begin(); iter != g_OnMi

lcalqf的专栏 6585

BeckHoff <--> ABB 机器手 Profinet 通讯

本文介绍了BeckHoff PLC与ABB机器人通过PROFINET通信的实现方案。主要内容包括:1)通信接口的详细变量定义,涵盖输入/输出信号、设备状态监控、夹爪控制等关键功能位;2)全局数据结构和变量配置说明;3)机器人任务控制程序的实现方法,包括参数校验、任务指令下发和状态监控机制;4)重点分析了任务调度功能块的代码逻辑,涉及慢速模式处理、多参数配置和执行状态判断。该方案通过结构化变量定义和模块化程序设计,实现了PLC对机器人作业的精确控制,为工业自动化系统集成提供了可靠通信范例。

工控智联驿站 1032

FIFO的工作原理及其设计

FIFO( First Input First Output)简单说就是指先进先出。FIFO存储器是一个先入先出的双口缓冲器,即第一个进入其内的数据第一个被移出,其中一个口是存储器的输入口,另一个口是存储器的输出口。对于单片FIFO来说,主要有两种结构:触发导向结构和零导向传输结构。触发导向传输结构的FIFO是由寄存器阵列构成的,零导向传输结构的FIFO是由具有读和写地址指针的双口RAM构成。FIFO与普通RAM存储器的是没有外部读写地址线(指针),使用方便,但。

Jackiezhang1993的博客 2万+

std::map 删除指定条件的元素

在C++开发中,std::map是经常使用到的容器,由键值就可以取出对应的值。 在使用map时,如果想从map中删除符合某一条件的元素,应该如何操作?

GreenArrowMan-优快云博客 2万+

自动驾驶开发者必看:nuscenes数据集23类物体标注全解析(附避坑指南)

本文深入解析nuscenes数据集的23类物体标注系统,为自动驾驶开发者提供全面的标注规范解读和实战避坑指南。涵盖多模态数据组织、类别细分规则、属性系统应用技巧以及标注质量验证方法,帮助开发者高效利用这一标杆数据集提升模型性能。

weixin_29041767的博客 256

C++ map 插入元素,删除元素

C++ map 插入元素,删除元素

weixin_44075027的博客 2907

基于GPU的GEMM矩阵相乘运算优化

从上图中我们可以看到三种处理方法。第一种是将A和B矩阵分块,第二种方法是将C和B矩阵分块,第三种方法是将C和A矩阵分块。GEMM的子任务是GEPP或GEMP;最小粒度的任务是GEBP或GEPB或点乘。

weixin_55035144的博客 2155

陀螺仪及四元数解算

陀螺仪 四元数

zb313982521的博客 2005

C++中std::map容器中元素删除方法汇总

的各种删除元素方法,包括:按 key 删除、按 iterator 删除、按条件删除(比如满足某个条件的元素),并配合一些遍历操作来看效果。:若要删除大量元素,使用范围删除比单个 key 删除更高效。,同时避免 iterator 失效问题。:O(log n + k),k 为删除元素个数。会调用元素的析构函数,复杂对象可能开销大。返回的新 iterator 来保证安全。下面一个更高级的示例,演示如何在循环中。

qq_36812406的博客 1690

保姆级教程:用YOLOv5s训练PCB缺陷检测模型(附北大公开数据集)

本文提供了一份基于YOLOv5s的PCB缺陷检测模型从零开始的完整实战教程。详细解析了如何使用北大公开数据集,涵盖环境搭建、数据处理、模型训练、性能评估及优化部署全流程,并针对工业场景中常见的类别不均衡问题给出了具体解决方案,旨在帮助开发者快速构建高精度的自动化质检系统。

weixin_28285943的博客 308

C++ STL 遍历 map 的时候如何删除其中的 element

首先看一段他人的一段文章:from: http://www.cnblogs.com/super119/archive/2011/10/11/2207541.html 我们通过map的erase(iterator it)方法删除元素的时候,如果此时erase处于遍历map的代码中,那么调用erase就需要小心一些。因为erase会导致输入参数iterator变的无效,从而影响后续的it++遍历

JoeBlackZQQ的专栏 2050

YOLOv11改进策略【独家融合改进】| MobileNetV4+BiFPN,轻松实现降参涨点,适用专栏内所有的骨干替换

可扩展的高效物体检测BiFPN(加权双向特征金字塔网络)

Limiiiing的博客 2361

深度学习工具包 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")

std::map的安全遍历并删除元素的方法

std::map的安全遍历并删除元素的方法 首先我们讲遍历std::map, 大部分人都能写出第一种遍历的方法,但这种遍历删除的方式并不太安全。 第一种 for循环变量: #include<map> #include<string> #include<iostream> using namespace std; int main() { map...

大隐隐于野 2246

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

C++ std:map深入解析与用法指南

C++ std::map 深入解析与用法指南

weixin_74396256的博客 6844

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

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

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

C++ STL标准库:std::map std::multimap 插入元素insert() 擦除元素erase()的使用

#include <iostream> #include <map> using namespace std; typedef pair<int, double> CustomPair; void Print(map<int,double>& m) { map<int, double>::iterator it; for(it=m.begin();it!=m.end();it++) { CustomPair p1=(pai

超级大洋葱的博客 2245

循环遍历 std:map 并删除元素解决方案

循环遍历 std::map 并删除元素 C/C++ code int main(int argc, char* argv[]) { map<string, string> mapData; mapData["a"] = "aaa"; mapData["b"] = "bbb"; mapData["c"] = "ccc"; for (map<string, string>::iterator i=mapData.begin(

looklight的博客 3240

超级简单易懂!!!std::map 和 std::unordered_map的区别!

C++标准模板库(STL)提供了多种容器类型,用于存储和管理数据集合。其中,`std::map`和`std::unordered_map`是两种常用的关联容器,它们都允许用户通过键来存取值。

Eason_jun的博客 1478

【std::map】与std::unordered_map操作差异

本文对比了C++中unordered_map和map的核心操作差异。

优快云_RTKLIB的博客 876

std::map 通过遍历删除满足某些条件元素的两种方式

方法一: [cpp] view plaincopy std::map mapTest;  bool TestVal(const std::string & val);    ......  std::map::iterator it = mapTest.begin();  while(it != mapTest.end())  {           if(TestVal(

leo115的专栏 2312

关于STD中常用容器vector/list/map遍历条件删除元素的问题

在我们开发过程中常常会用到STD中的一些容器,容器的使用无非就是增删修查等操作,今天要说的是关于STD中常用容器vector/list/map遍历条件删除元素的问题。 我们知道直接遍历容器的所有元素很简单,直接for循环就阔以,但是如果是遍历容器并且删除满足条件的元素的时候就要注意了,因为如果按照常规的遍历直接删除的方式会出错(此处可以自己写个简单的测试用例验证一下)...

xym352860763的博客 1239

C++标准库中std::map和std::unordered_map对比及如何选择

std::map和std::unordered_map都是一种存储{key, value}的容器,并提供成员函数来高效地插入、搜索和删除键值对。 顾名思义,std::map是有序的,std::unordered_map是无序的。 后者以前叫做hash_map。

photon222的博客 1万+

C++ std::map 用法 插入 取值 删除 遍历

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力 初始化: #include "map" //引入头文件 std::map <int, std::string> _map1; //初始化 //c++11中引入的,可以直接在初始化时赋值 std::map <int, std::string> _map = { {0,"11"}, {2

软件工程小施同学 的专栏 1万+
上一篇: C++标准库(第2版)第7章map的一个运行期指定排序规则的示例
下一篇: 对QMap中的key进行自定义排序
hp_cpp
博客等级 码龄11年 310粉丝 218原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值