很早之前我看到有大佬在用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的哈希應用。將會在我的下一篇博客研究一下。
傳送門!!!<——(還沒寫好)