C++里map比较像数组,可是不需要写它的大小。下面我给大家看一下他的用法。
1、定义方法
map<>里面可以填任意类型。如:
#include <bits/stdc++.h>
using namespace std;
map <int, string> mp;
#include <bits/stdc++.h>
using namespace std;
map <char, int> mp;
等等等等。
2、调用及定义map里的变量
像数组一样,可以写成map[]的形式,[]里面要写定义map时的第1个类型的变量,像整数一样,map里的变量可以直接用“=”进行赋值。下面代码可以参考一下。
#include <bits/stdc++.h>
using namespace std;
map <string, int> name_age;
int main() {
name_age["John"] = 25;
name_age["Alice"] = 10;
cout << name_age["John"] << " " << name_age["Alice"];
return 0;
}
运行结果为:
25 10
3、注意事项
1、如果map[i]没有被定义过,则map[i]=0 。
大家不妨试一下下面的代码:
#include <bits/stdc++.h>
using namespace std;
map <string, int> mp;
int main() {
mp["Alice"] = 10;
cout << mp["Bob"];
return 0;
}
2、如果调用时[]里填的值是定义时第2个变量的类型的变量,编译器会报错。如下面代码是错的。
#include <bits/stdc++.h>
using namespace std;
map <string, int> mp;
int main() {
mp[10] = "Alice";
cout << mp[10];
return 0;
}