之前用python,写着很方便,特别是里面有一种数据类型,字典。
比如 student_scores = {}
student_scores ["xiaoming"] = 80;
student_scores ["lucy"] = 90;
可以很方便的直接使用字符串作为key,来获取其中的value,可以既方便的和JSON数据配合使用 或者 很多场景减少大量重复代码。
那么c++里面有没有类似的呢。也是有的,那就是std::map
关于map的定义:
map<key,value> student_scores;
第一个是key的类型,第二个是value 的类型。key可以是字符串,value可以是任何类型,包括class,struct,vector,wstring,int,char等任意数据类型。
我们用C来实现上面学生的定义
#include <string>
#include <map>
using namespace std;
void main(){
map<wstring,int> student_scores;
//添加
student_scores [L"小明"] = 80;
student_scores [L"lucy"] = 90;
//遍历:
//it.first就是key,it.second就是value
for(auto&it:student_scores){
printf("名字:%s, 分数:%d\n",WstringToString(it.first).c_str(),it.second);
}
//判断是否存在
if (student_scores .find(L"小明") == student_scores .end())
printf("不存在小明的分数");
else
printf("找到小明的分数");
//添加和修改 都是一样的
student_scores[L"小明"] = 90;
//读取
printf("lucy的分数:%d\n",student_scores[L"lucy"]);
//删除
student_scores.erase(L"小明");
}
删除操作:
1 map.erase(k):删除map中键为k的元素。返回size_type类型的值,表示删除的元素个数;
2 map.erase(p):从map中删除迭代器p所指向的元素。p必须指向map中确实存在的元素,而且不能等于map.end(),返回 void类型;
3 map.erase(b,e):从map中删除一段范围内的元素,该范围由迭代器对b和e标记。b和e必须标记map中的一段有效范围:即b和e都必须指向map中的元素或最后一个元素的下一个位置。而且,b和e要么相等(此时删除的范围为空),要么b所指向的元素必须出现在e所指向的元素之前,返回void类型