[TOC]
這幾天由于C++程序設(shè)計的原因,我花了3天時間自學(xué)了一下C++。由于課程設(shè)計涉及到了MYSQL數(shù)據(jù)庫的操作,之前用到的編程語言如JAVA、PHP都有類似鍵值對數(shù)組的東西。而C++中的map()函數(shù)也是一樣的。
map函數(shù)是什么?
Map是c++的一個標(biāo)準(zhǔn)容器,她提供了很好一對一的關(guān)系,在一些程序中建立一個map可以起到事半功倍的效果,總結(jié)了一些map基本簡單實用的操作!
簡單的來說: Map是STL的一個容器,它提供一對一的hash。
它的標(biāo)準(zhǔn)形式為
Map<int, string> mapStudent;
- 第一個為關(guān)鍵字(key),再函數(shù)中只能map出現(xiàn)一次()
- 第二個為該關(guān)鍵字的值 (value)
形式就像 arr{
[0]=>['id']
}
這種形式的數(shù)組
map函數(shù)的構(gòu)造方法
剛剛我們上面說的
Map<int, string> mapStudent;
只是構(gòu)造函數(shù)的一種,還有一些常用的構(gòu)造函數(shù)
如:
| A | B |
|---|---|
| map<string , int >mapstring | map<int ,string >mapint |
| map<sring, char>mapstring | map< char ,string>mapchar |
| map<char ,int>mapchar | map<int ,char >mapint |
map的使用
- 引入頭文件
#include<map> //引入map頭文件
#include<string> //為了等會好用sting類
using namespace std; //一定要寫上命名空間
- 變量聲明
Map<int,string> test;
- 插入數(shù)據(jù)
Map插入數(shù)據(jù)有三種方式
- 用insert函數(shù)插入pair
test.insert(pair<int, string>(1, "test"));
例子程序:
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
map<int, string > test;
test.insert(pair<int, string>(1, "test"));
cout << 輸出<< test[1];
return 0;
}
結(jié)果:
輸出 test
- 用"array"方式插入
test[0]= "xusupeng";
如:
int main()
{
map<int, string > test;
test[1] = "xusupeng";
cout << test[1];
return 0;
}
結(jié)果:
xusupeng
用insert函數(shù)插入value_type數(shù)據(jù)
這種和第一種插入效果是一樣的,再這里就不再贅述了。3種插入方式的區(qū)別
雖然都可以實現(xiàn)數(shù)據(jù)的插入,但是它們是有區(qū)別的,當(dāng)然了第一種和第二種在效果上是完成一樣的,用insert函數(shù)插入數(shù)據(jù),在數(shù)據(jù)的插入上涉及到集合的唯一性這個概念,即當(dāng)map中有這個關(guān)鍵字時,insert操作是插入數(shù)據(jù)不了的,但是用數(shù)組方式就不同了,它可以覆蓋以前該關(guān)鍵字對應(yīng)的值。大家可以自己代碼去測試一下
- 遍歷map(一維數(shù)組)
C++的遍歷也可以和java一樣用iterator
1.定義一個迭代器指針,使這個指針指向map的開始位置- it->first即我們定義數(shù)組的key,it->second即我們的值
#include<map>
#include<string>
#include<iostream>
using namespace std;
int main()
{
typedef map<int, string> Map;
Map test;
Map::iterator it; //定義一個迭代器指針
test[0] = "test1";
test[2] = "test2";
test[3] = "test3";
test[4] = "test4";
for (it = test.begin(); it != test.end(); it++) //指針指向map數(shù)組的開頭位置
{
cout << it->first << " "<<it->second<<endl;
}
return 0;
}
代碼結(jié)果:
0 test1
2 test2
3 test3
4 test4
(二維數(shù)組)
抱歉我試了半天都不能行,如果有會的請教教我
參考:
[1]:http://blog.csdn.net/sunshinewave/article/details/8067862
[2]:http://www.jb51.net/article/96053.htm
[3]: http://blog.csdn.net/sunquana/article/details/12576729