起因
最近在学习opengl中 一节时候,遇见了如下代码:
std::mapsorted;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