c++中STL map的用法
时间: 2024-03-18 19:38:01 浏览: 91
C++中的STL中map是一种关联容器,它提供了一种键值对的映射关系。下面是两个关于C++中STL map用法的例子:
1. 插入和访问元素[^1]:
```cpp
#include <map>
#include <string>
#include <iostream>
using namespace std;
int main() {
map<int, string> mapStudent;
mapStudent[1] = "student_one"; // 插入键值对
mapStudent[1] = "student_two"; // 更新键值对
mapStudent[2] = "student_three";
map<int, string>::iterator iter;
for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++) {
cout << iter->first << ' ' << iter->second << endl; // 访问键值对
}
}
```
2. 获取map的大小:
```cpp
#include <map>
#include <iostream>
using namespace std;
int main() {
map<int, string> mapStudent;
mapStudent[1] = "student_one";
mapStudent[2] = "student_two";
mapStudent[3] = "student_three";
cout << "Size of mapStudent: " << mapStudent.size() << endl; // 获取map的大小
}
```
阅读全文