#include <iostream> #include <map> using namespace std; int main() { map<int, string> person; person.insert(pair<int,string>(1,"bob")); person.insert(map<int, string>::value_type(2, "tony")); person.insert(pair<int, string>(3, "jack")); for (map<int,string>::iterator i= person.begin();i!= person.end();i++) { cout << i->first <<":"<< (i->second).c_str() << endl; } cout << "add 4 rose" << endl; person[4] = "rose"; for (map<int, string>::iterator i = person.begin(); i != person.end(); i++) { cout << i->first << ":" << (i->second).c_str() << endl; } person.erase(1); cout << "erase bob" << endl; for (map<int, string>::iterator i = person.begin(); i != person.end(); i++) { cout << i->first << ":" << (i->second).c_str() << endl; } cout << "insert jack2" << endl; pair< map<int,string>::iterator,bool > pa = person.insert(pair<int, string>(3, "jack2")); if (!pa.second) { cout << "inset err" << endl; } for (map<int, string>::iterator i = person.begin(); i != person.end(); i++) { cout << i->first << ":" << (i->second).c_str() << endl; } cout << "person[3] = jack2" << endl; person[3] = "jack2"; for (map<int, string>::iterator i = person.begin(); i != person.end(); i++) { cout << i->first << ":" << (i->second).c_str() << endl; } cout << "get 3" << endl; if (person.count(3)) { cout << "R3:"<<person[3].c_str() << endl; } cout << "get 4" << endl; map<int, string>::iterator itmp = person.find(4); if (itmp != person.end()) { cout << "R4:" << (itmp->second).c_str() << endl; } cout << "clear" << endl; person.clear(); for (map<int, string>::iterator i = person.begin(); i != person.end(); i++) { cout << i->first << ":" << (i->second).c_str() << endl; } cout << "end press anykey." << endl; getchar(); }
显示:
1:bob
2:tony
3:jack
add 4 rose
1:bob
2:tony
3:jack
4:rose
erase bob
2:tony
3:jack
4:rose
insert jack2
inset err
2:tony
3:jack
4:rose
person[3] = jack2
2:tony
3:jack2
4:rose
get 3
R3:jack2
get 4
R4:rose
clear
end press anykey.