map是STL的一个关联容器,以键值对存储的数据。
每个关键字在map中只能出现一次,关键字不能修改,值可以修改。
使用的时候,需要引入头文件 #include
map
test_map; test_map.insert({1, "Jack"});
test_map.insert({2, "Rose"});
test_map.erase(2);
map
::iterator it; for ( it= test_map.begin(); it != test_map.end(); it++) {
cout << it->first << " " << it->second << endl;
}
cout << test_map.find(1)->second << endl; //输出“键”为1的值
(1)test.cpp内容如下:
#include
#include
using namespace std;
int main(){
map
test_map.insert({1, "Jack"});
test_map.insert({2, "Rose"});
cout << "Original map :" << endl;
map
for ( it= test_map.begin(); it != test_map.end(); it++) {
cout << it->first << " " << it->second << endl;
}
test_map.erase(2);
cout << "Deleted map :" << endl;
map
for ( it0= test_map.begin(); it0 != test_map.end(); it0++) {
cout << it0->first << " " << it0->second << endl;
}
cout << test_map.find(1)->second << endl;
}
(2)运行
g++ test.cpp -o test
./test
(3)结果
Original map :
1 Jack
2 Rose
Deleted map :
1 Jack
Jack