map<string, string>::iterator用法
时间: 2024-04-15 09:22:25 浏览: 121
map<string, string>::iterator是C++中用于遍历和操作map容器的迭代器类型。它可以用来访问map中的键值对,并进行插入、删除、修改等操作。
使用map<string, string>::iterator的一般步骤如下:
1. 定义一个map容器,并插入一些键值对:
```cpp
map<string, string> myMap;
myMap["key1"] = "value1";
myMap["key2"] = "value2";
myMap["key3"] = "value3";
```
2. 声明一个map<string, string>::iterator类型的迭代器,并将其初始化为map的起始位置:
```cpp
map<string, string>::iterator it = myMap.begin();
```
3. 使用迭代器进行遍历和操作:
- 访问当前键值对的键和值:
```cpp
cout << "Key: " << it->first << ", Value: " << it->second << endl;
```
- 迭代器自增,指向下一个键值对:
```cpp
it++;
```
- 插入新的键值对:
```cpp
myMap.insert(make_pair("key4", "value4"));
```
- 删除当前迭代器指向的键值对:
```cpp
it = myMap.erase(it);
```
- 修改当前迭代器指向的值:
```cpp
it->second = "new value";
```
4. 使用循环遍历整个map容器:
```cpp
for (map<string, string>::iterator it = myMap.begin(); it != myMap.end(); it++) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)