C++ STL 中 map 头文件的用法详解
map 头文件是 C++ STL 的一部分,提供了多种 mapa 数据结构的实现,该数据结构可以存储键值对,并提供了许多有用的函数来操作这些对。在本文中,我们将详细介绍 map 头文件的一些常用用法。
1. 基本用法
map 的基本用法是使用键值对来存储数据。例如,我们可以使用以下代码来创建一个 map:
```cpp
map<char, int> mymap;
```
然后,我们可以使用 `[]` 运算符来插入键值对:
```cpp
mymap['b'] = 100;
mymap['a'] = 200;
mymap['c'] = 300;
```
使用 ` iterator` 可以遍历 map 中的所有键值对:
```cpp
for (it = mymap.begin(); it != mymap.end(); ++it)
cout << (*it).first << "=>" << (*it).second << endl;
```
2. count 用法
`count` 函数可以用于统计 map 中某个键的出现次数。如果 map 中存在该键,则返回 1,否则返回 0。
```cpp
size_type count(key_type x) const;
```
例如,我们可以使用以下代码来统计 map 中键 'a' 的出现次数:
```cpp
if (mymap.count('a') > 0)
cout << "Key 'a' exists in the map." << endl;
```
3. equal_range 用法
`equal_range` 函数可以用于获取 map 中某个键的迭代器范围。
```cpp
pair<iterator, iterator> equal_range(const key_type& x);
pair<const_iterator, const_iterator> equal_range(const key_type& x) const;
```
例如,我们可以使用以下代码来获取 map 中键 'a' 的迭代器范围:
```cpp
pair<map<char, int>::iterator, map<char, int>::iterator> pRet;
pRet = mymap.equal_range('a');
cout << "lower bound points to : " << endl;
cout << pRet.first->first << "=>" << pRet.first->second << endl;
cout << pRet.second->first << "=>" << pRet.second->second << endl;
```
4. erase 与 find 用法
`erase` 函数可以用于删除 map 中的某个键值对。
```cpp
void erase(iterator position);
size_type erase(const key_type& x);
void erase(iterator first, iterator last);
```
例如,我们可以使用以下代码来删除 map 中键 'b' 的记录:
```cpp
mymap.erase(mymap.find('b'));
```
`find` 函数可以用于查找 map 中某个键值对。
```cpp
iterator find(const key_type& x);
const_iterator find(const key_type& x) const;
```
例如,我们可以使用以下代码来查找 map 中键 'a' 的记录:
```cpp
map<char, int>::iterator it = mymap.find('a');
if (it != mymap.end())
cout << "Key 'a' exists in the map." << endl;
```
5. insert 用法
`insert` 函数可以用于插入新的键值对到 map 中。
```cpp
pair<iterator, bool> insert(const value_type& x);
iterator insert(iterator position, const value_type& x);
void insert(iterator first, iterator last);
```
例如,我们可以使用以下代码来插入新的键值对:
```cpp
pair<map<char, int>::iterator, bool> pRet;
pRet = mymap.insert(pair<char, int>('d', 400));
if (pRet.second)
cout << "Perfect!" << endl;
```
map 头文件提供了许多有用的函数来操作 mapa 数据结构,使得我们可以更方便地处理键值对数据。