std::map看来可以被淘汰了?可以用vector来替代,而且更好

C++最经典的三大容器Vector、Map、List C++中的容器可以分为好多种,常见的有顺序容器:向量(vector)、双端队列(deque)、列表(list)。还有关联容器:集合(set)、多重集合(multiset)、映射(map)和多重映射(multimap)。容器有太多,下面就来讲讲用得到也最常用的三种容器vector、list、map。 第一种:Vector容器 示意图: 特点: 地址不变,内存空间连续,所以在中间进行插入和删除时会造成内存块拷贝,如果插入的是结构体或者类,则会造成构造和析构,性能不是特别高,对结尾元素操作最快。 下 阅读详情

vector的优势在于内存连续,可以提前申请好。

排序的时候可以用std::sort,可以自己提供排序准则。

查找的时候,可以使用std::lower_bound,或者std::binary_search。

前者可以返回位置,但这个位置所指向的值并不一定和你要查询的值相等。

后者倒是去精准匹配值,只返回bool,查不到就是false,查到了就是true。

而std::map,insert的时候,需要new出节点内存。这些内存不连续。

要是不需要一个排好序的map,仅仅是查询的话,也可以用unordered_map,

来一个lower_bound的例子

#include <algorithm>
#include <vector>
#include <string>

struct Person {
    std::string name;
    int age;
};

// 自定义比较函数
bool compareByAge(const Person& a, const Person& b) {
    return a.age < b.age;
}

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 35}
    };
    
    // 查找年龄不小于 28 的人
    Person target = {"", 28};
    auto it = std::lower_bound(people.begin(), people.end(), target, compareByAge);
    
    if (it != people.end()) {
        std::cout << "找到年龄不小于 28 的人: " << it->name 
                  << ", 年龄: " << it->age << std::endl;
    }
    
    return 0;
}

参考:

You may not need std::map - CPP Optimizations diary

原文如下:

Do you actually need to use std::map?

std::map is one of the most known data structures in C++, the default associative container for most of us, but its popularity has been decreasing over the years.

Associative containers are used when you have pairs of key/value and you want to find a value given its

C++ std::map 核心操作与性能优化全解析 关联容器是C++标准库中用于存储键值对数据的重要组件,其核心思想是通过键快速访问关联的值,类似于字典的查找机制。这类容器基于高效的数据结构实现,如红黑树或哈希表,确保了在数据量增长时仍能保持稳定的操作性能。在软件开发中,关联容器常用于实现缓存机制、频率统计、配置管理等场景,能显著提升程序的运行效率与代码可读性。本文以C++中的std::map为例,深入剖析其底层红黑树原理,详细讲解插入、查找、删除等核心操作,并对比unordered_map的性能差异,帮助开发者根据有序性需求与性能要求做出正确选择,避免迭代 阅读详情

相关推荐

C++ std::list核心操作与迭代器稳定性深度解析

在C++标准模板库(STL)中,容器是管理数据集合的核心组件,其设计直接影响程序的性能与安全性。链表作为一种基础数据结构,通过节点间的指针链接实现动态存储,其核心优势在于任意位置的O(1)时间复杂度插入与删除操作,代价是牺牲了随机访问能力。这种特性使其在需要频繁修改序列、且对迭代器稳定性要求极高的场景中具有独特的技术价值,例如实现LRU缓存、网络连接管理或游戏实体列表。std::list是STL对双向循环链表的实现,它通过精巧的哨兵节点设计和成员函数封装,不仅提供了push_back、insert、eras

weixin_34241036的博客 285

(超详细)Qt入门和配置Visual Studio的Qt环境

内容写了Qt入门,创建并编写第一个Qt程序,以及配置VS编写Qt程序的环境。(超级详细)

LY549826LY549264的博客 7681

如何用Python+Librosa实现轴承异响检测?5步搞定工业设备故障预警

本文详细介绍了如何利用Python和Librosa库,通过5个步骤构建工业轴承异响检测与故障预警系统。从音频采集、预处理、频谱特征提取,到构建机器学习模型并进行实时监测,提供了完整的代码级解决方案。该方法能有效识别轴承早期故障特征,实现低成本、高效的设备预测性维护。

rnn9storyteller的博客 634

PCL1.12.1+VTK9.1+Qt5.14.2实战:解决QVTKOpenGLNativeWidget点云渲染窗口初始化报错问题

本文针对PCL1.12.1、VTK9.1与Qt5.14.2集成开发中,QVTKOpenGLNativeWidget点云渲染窗口初始化时出现的报错与黑屏问题,提供了深度分析与两种实战解决方案。核心在于理解VTK版本升级导致的渲染窗口类型不匹配,并指导开发者通过显式创建vtkGenericOpenGLRenderWindow或利用窗口ID嵌入,正确初始化并绑定可视化组件,从而稳定实现点云渲染。

weixin_29284657的博客 223

用scons编译STM32F103工程

想用vscode来实现代码的编辑与调试代码,原先这个工程是用STM32CUBEIDE建立的,参照STM32CUBEIDE的编译过程,编写了下面的scons脚本,scons是初次了解,既然是python脚本,那么会什么就怎么写吧。 import os import sys import glob cross_compiler_prefix = 'arm-none-eabi-' CC = cross_compiler_prefix+'gcc' CXX = cross_compiler_prefix+'g+

cylinc的专栏 1624

【数据库】银行/信贷业务测试工作中涉及的数据库表格

银行/信贷业务测试工作中涉及的数据库表格,金融信贷测试人必看!

孤之鹜的博客 1175

Flowable前端可视化配置动态审批人:告别硬编码,实现部门领导、项目经理自动分配

本文详细介绍了Flowable前端可视化配置动态审批人的全栈解决方案,通过表达式分配、监听器分配等动态审批人机制,实现从硬编码到智能分配的转变。文章提供了前端扩展bpmn-js设计器、后端动态解析实现方案及性能优化建议,帮助企业应对组织架构变动,提升审批流程的灵活性和效率。

weixin_30352645的博客 476

关于LIO-SAM编译时出现错误 /usr/bin/ld: 找不到 -lBoost::timer

关于LIO-SAM编译时出现错误: 下载LIO-SAM代码 进入LIO-SAM文件夹,通过以下代码编译: mkdir build cd build cmake .. make 报错: /usr/bin/ld: 找不到 -lBoost::timer collect2: error: ld returned 1 exit status CMakeFiles/lio_sam_imuPreintegration.dir/build.make:759: recipe for target 'devel/lib/li

wwtx的博客 3648

半小时搞定Yolov5安装配置及使用(详细过程)

Yolov51. 下载Yolov52. 安装Yolov5 在下载配置Yolov5前,先要安装好Anaconda环境,可参考之前博文:最新Anaconda3的安装配置及使用教程(详细过程) 1. 下载Yolov5 首先下载Yolov5源码: Yolov5 Github地址:https://github.com/ultralytics/yolov5 直接git clone到本地工作目录,等待下载完成: Yolov5代码目录架构: 2. 安装Yolov5 源码下完后,下面开始安装Yolov5所需模块,

HowieXue 薛永浩的博客 12万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

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

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

上一篇: 六君子:特殊成员函数模板(Special Member Functions)
下一篇: doxygen注释头文件时,一定得有@file
tumu_C
博客等级 码龄19年 377粉丝 195原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值