博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
stl map
阅读量:7124 次
发布时间:2019-06-28

本文共 2701 字,大约阅读时间需要 9 分钟。

起因

最近在学习opengl中 一节时候,遇见了如下代码:

std::map
sorted;for (GLuint i = 0; i < windows.size(); i++) // windows contains all window positions{ GLfloat distance = glm::length(camera.Position - windows[i]); sorted[distance] = windows[i];}

当时并不明白map到底是什么东西,随后便了解了一下。

什么是 stl map

map是STL的一种关联容器,类似与哈系表,提供一对一的数据处理能力(其中第一个字称为 关键字, 且每个关键字只能在map中出现一次;第二个数据 是关键字所对应的值)。map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的。

map的简单用法

一. map构造

template < class Key, class T, class Compare = less
,       class Allocator = allocator
> > class map;

key:关键值的类型。在map对象中的每个元素是通过该关键值唯一确定元素的。

T:映射值的类型。在map中的每个元素是用来储存一些数据作为其映射值

例如: std::map<float, glm::vec3> sorted; std::map<int, string> mapStudent;

二. 数据插入

1.pair 插入

//pair 方式插入数据                mapStudent.insert(pair
(1,"xiao ming")); mapStudent.insert(pair
(2,"xiao li")); mapStudent.insert(pair
(3,"xiao jia"));

2.数组方式

mapStudent[1] =  "student_one"; mapStudent[2] =  "student_two"; mapStudent[3] =  "student_three";

第一节opengl中所用到的就是以数组的方式插入数据。

map遍历 与 查找

1.前向迭代器

map
::iterator iter; for (iter = mapStudent.begin();iter != mapStudent.end();++iter) { cout<
first<<" "<
second<

2.反向迭代器

map
::reverse_iterator iter2; for(iter2 = mapStudent.rbegin(); iter2 != mapStudent.rend();++iter2) { cout<
first<<" "<
second<

3.数组的方式遍历

/* 遍历3:数组方式 。 这种方式只是适合key值是顺序排列的*/        for (int i = 1; i <= size; i++)        {                cout<
<

4.find查找

map
::iterator find; find = mapStudent.find(2); if(find != mapStudent.end()) { cout<<"the value is:"<
second<

观察发现:用find查找数据,返回值是 map的迭代器,如果map中没有要查找的数据,则返回的迭代器为end函数返回的迭代器。

整合程序:

#include #include 
#include
using namespace std;int main (){ map
mapStudent; //pair 方式插入数据 /* mapStudent.insert(pair
(1,"xiao ming")); mapStudent.insert(pair
(2,"xiao li")); mapStudent.insert(pair
(3,"xiao jia")); */ //数组的方式 mapStudent[1] = "student_one"; mapStudent[2] = "student_two"; mapStudent[3] = "student_three"; /* map的遍历 1:前向迭代器 */ map
::iterator iter; for (iter = mapStudent.begin();iter != mapStudent.end();++iter) { cout<
first<<" "<
second<
::reverse_iterator iter2; for(iter2 = mapStudent.rbegin(); iter2 != mapStudent.rend();++iter2) { cout<
first<<" "<
second<
::iterator find; find = mapStudent.find(2); if(find != mapStudent.end()) { cout<<"the value is:"<
second<

转载地址:http://yteel.baihongyu.com/

你可能感兴趣的文章
python装饰器
查看>>
bzoj 3196: Tyvj 1730 二逼平衡树
查看>>
Linux学习第三篇之Linux常用命令——命令格式与目录处理命令ls
查看>>
Unable to execute dex: method ID not in [0, 0xffff]: 65536
查看>>
【人生】不管你挣多少, 钱永远是问题
查看>>
DG备库无法接受主库归档日志之密码文件
查看>>
[bzoj 2555]Substring
查看>>
tab标签
查看>>
ecshop新增银联企业网银支付方式
查看>>
Angular5学习笔记 - 配置NG-ZORRO(八)
查看>>
使用Netty实现HTTP服务器
查看>>
JAVA开发工具eclipse中@author怎么改
查看>>
存储引擎与锁
查看>>
sqlog连接虚拟机mysql服务
查看>>
出错,网页显示不出内容
查看>>
Spring中的后置处理器BeanPostProcessor讲解
查看>>
《FPGA全程进阶---实战演练》第十四章 蜂鸣器操作
查看>>
浅析firmware完整生存和使用流程 【转】
查看>>
《30天自制操作系统》笔记(01)——hello bitzhuwei’s OS!【转】
查看>>
MMU介绍【转】
查看>>