程序示例
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<char, int> mymap; //使用map
mymap.insert(pair<char, int>('a', 1));
mymap.insert(pair<char, int>('b', 2));
mymap.insert(pair<char, int>('c', 3));
map<char, int>::iterator it;
for (it = mymap.begin(); it != mymap.end(); it++) {
cout << "key=" << it->first <<": " << it->second << endl;
}
cout << "============================" << endl;
mymap.insert(pair<char, int>('c', 30)); //插入数据不能覆盖
for (it = mymap.begin(); it != mymap.end(); it++) {
cout << "key=" << it->first << it->second << endl;
}
cout << "============================" << endl;
mymap['c'] = 30; //插入数据可以覆盖
mymap['d'] = 4;
for (it = mymap.begin(); it != mymap.end(); it++) {
cout << "key=" << it->first << it->second << endl;
}
return 0;
}
|