C++相关
STL—map容器
定义: map<key的数据类型,value的数据类型> 容器名字。
map容器:STL 关联容器。一对一的存储形式,实现原理 红黑树。键值对存储型, key -value 可以是任意数据类型,自动根据key进行排序。容器的key是唯一的。
存储操作: 如果对map容器以[]形式去访问,但是这个key不存在于容器里面,那么相当于会插入一个这个key对应空的值进行存储。用insert进行存储,如果是中括号的那种存储方式,容器已经存在对应的key,那么会进行修改。如果使用insert,容器已经存在对应的key,那么insert不生效。
读取操作: 容器[key] 访问容器的 key对应的value。at(key)来读取的话,不存在,会出错。
#include <iostream>
#include <map>
using namespace std;
struct SStudent
{
SStudent()
{
}
SStudent(int nInID, string strInName, int nInAge)
{
nID = nInID;
strName = strInName;
nAge = nInAge;
}
int nID;
string strName;
int nAge;
};
int main()
{
map<int, SStudent> mapStudent;
SStudent stu1 = mapStudent.at(1005);
//存储:
mapStudent[1001] = SStudent(1001, "张三", 20);
mapStudent[1002] = SStudent(1002, "李四", 30);
mapStudent[1012] = SStudent(1012, "王五", 30);
mapStudent[1001] = SStudent(1001, "张二", 20);//修改1001对应的值。
mapStudent.insert(pair<int, SStudent>(1010, SStudent(1010, "王八", 30)));
mapStudent.insert(pair<int, SStudent>(1002, SStudent(1002, "李三", 30)));
}