map 宣告需要兩種 class 對應, 若是要做 string mapping array 的話, 就宣告為
map<string, string>
即可, 接下來可以應用 insert 方法, 將資料存入, 另外還有更方便的方法, 就是利用 [] oprator, 以下為一個 sample code,
代碼: 選擇全部
#include <string>
#include <map>
...
map<string, string> m1;
map<string, string>::iterator mp;
pair<string, string> p1;
p1.first = "a";
p1.second = "1";
m1.insert(p1);
p1.first = "b";
p1.second = "2";
m1.insert(p1);
m1["c"]="3";
m1["d"]="4";
MessageBox(m1["b"].c_str());
string out;
for(mp=m1.begin();mp!=m1.end();mp++)
{
out = out + mp->first + "=" + mp->second + "n";
}
MessageBox(out.c_str());
特別要注意的地方是, 若是使用 m1["ab"] 來找資料時, 若資料不存在, 該 map 仍會自行寫入一筆 ab="" 的資料哦!
這個 map 型態真的很好用哦!
執行結果,