之前用python,寫著很方便,特別是里面有一種數(shù)據(jù)類型,字典。
比如 student_scores = {}
student_scores ["xiaoming"] = 80;
student_scores ["lucy"] = 90;
可以很方便的直接使用字符串作為key,來獲取其中的value,可以既方便的和JSON數(shù)據(jù)配合使用 或者 很多場景減少大量重復(fù)代碼。
那么c++里面有沒有類似的呢。也是有的,那就是std::map
關(guān)于map的定義:
map<key,value> student_scores;
第一個是key的類型,第二個是value 的類型。key可以是字符串,value可以是任何類型,包括class,struct,vector,wstring,int,char等任意數(shù)據(jù)類型。
我們用C來實現(xiàn)上面學(xué)生的定義
#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, 分?jǐn)?shù):%d\n",WstringToString(it.first).c_str(),it.second);
}
//判斷是否存在
if (student_scores .find(L"小明") == student_scores .end())
printf("不存在小明的分?jǐn)?shù)");
else
printf("找到小明的分?jǐn)?shù)");
//添加和修改 都是一樣的
student_scores[L"小明"] = 90;
//讀取
printf("lucy的分?jǐn)?shù):%d\n",student_scores[L"lucy"]);
//刪除
student_scores.erase(L"小明");
}
刪除操作:
1 map.erase(k):刪除map中鍵為k的元素。返回size_type類型的值,表示刪除的元素個數(shù);
2 map.erase(p):從map中刪除迭代器p所指向的元素。p必須指向map中確實存在的元素,而且不能等于map.end(),返回 void類型;
3 map.erase(b,e):從map中刪除一段范圍內(nèi)的元素,該范圍由迭代器對b和e標(biāo)記。b和e必須標(biāo)記map中的一段有效范圍:即b和e都必須指向map中的元素或最后一個元素的下一個位置。而且,b和e要么相等(此時刪除的范圍為空),要么b所指向的元素必須出現(xiàn)在e所指向的元素之前,返回void類型