【乱搞stl】c++ map 歪曲理解版。简单用法。

很早之前我看到有大佬在用map。。

我弱弱的跑上去问怎么用。。

结果大佬不屑于回答,让我自己去百度。。

结果查出来的都是奇奇怪怪看不懂的东西,,

都是什么迭代器。。。。

然后经过我的观察乱搞。弄出来了一种比较易懂的方法。。

如果我的理解有偏差,请大佬不要喷,看看就好

首先我们需要头文件

#include<map>
//下面两个可加可不加,取决你要不要用string
#include<iostream>
#include<cstring>

然后然后。。
你就可以定义一个map容器了吧。
map就是关于两个元素映射。
map<string,int>
就是一种pair,一种关联.
左边的是键值,key value
右边的是实值,Mapped Value
我们可以通过键值直接找到实值。
我也不知道时间复杂度多少,,不超过O(log n)就对了
如何把两个值连起来呢?
(下面是名字和学号连在一起)

#include<map>
#include<iostream>
#include<cstring>
using namespace std;
int main(){
    map<string,int> stumap;
    string studentname="ZhangSan";
    int studentID=1;
    stumap[string(studentname)]=studentID;
    cout<<stumap[string("ZhangSan")];
}

和数组一样好用。。。lalala;
只不过是要加一个 变量类型(XXX)而已
如果要根据value值找key值的话。。
再开一个反向的就好了啊。
(条件。value只对应一个key)
如果有重复。。参照百度。。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
using namespace std;
int main(){
    map<string,int> strmap;
    map<int,string> intmap;
    int n;
    string st;
    int x;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        cin>>st>>x;
        strmap[string(st)]=x;
        intmap[int(x)]=st;
    }
    int q;
    scanf("%d",&q);
    for(int i=1;i<=q;i++){
        cin>>st;
        cout<<strmap[string(st)]<<endl;
    }
    scanf("%d",&q);
    for(int i=1;i<=q;i++){
        cin>>x;
        cout<<intmap[int(x)]<<endl;
    }
}

result:
程序运行结果

map的哈希应用。将会在我的下一篇博客研究一下。
传送门!!!<——(还没写好)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章