c++将map的值减一
时间: 2023-11-24 08:04:09 浏览: 33
可以通过迭代器遍历 map 的每一个键值对,然后将值减一。示例代码如下:
```c++
#include <iostream>
#include <map>
int main() {
std::map<char, int> m {{'a', 2}, {'b', 3}, {'c', 4}};
// 遍历 map,并将每个值减一
for (auto it = m.begin(); it != m.end(); ++it) {
it->second--;
}
// 输出减一后的结果
for (const auto& [key, value] : m) {
std::cout << key << ": " << value << std::endl;
}
return 0;
}
```
输出结果为:
```
a: 1
b: 2
c: 3
```
注意,这里使用了 C++17 的结构化绑定(Structured Bindings)特性,如果你使用的是 C++11 或 C++14,可以改为:
```c++
for (const auto& p : m) {
std::cout << p.first << ": " << p.second << std::endl;
}
```
或者使用迭代器的 `->` 运算符访问键和值:
```c++
for (auto it = m.begin(); it != m.end(); ++it) {
std::cout << it->first << ": " << it->second << std::endl;
}
```
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)