C++ map修改指定key的value

本文探讨了如何在C++中正确修改map中指定key的value。常见的误解是使用insert操作来覆盖,但实际效果并不如预期。正确的做法不是通过insert,而是应该直接访问并更新键值对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  对于修改C++指定key的value,网上查了很多,都说直接insert就会覆盖原来的值,是否是这样的呢

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
// mapmodifykey.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    map<string, 
int> m_map;
    m_map.insert(make_pair(
"Michael Jordan"23));
    m_map.insert(make_pair(
"Kobe Bryant"8));
    m_map.insert(make_pair(
"James Harden"13));
    m_map.insert(make_pair(
"Chris Paul"3));
    map<string, 
int>::const_iterator iteMap = m_map.begin();
    cout << 
"==============旧值=============" << endl;
    
for(; iteMap != m_map.end(); ++ iteMap)
    {
        cout << iteMap->first;
        cout << 
":";
        cout << iteMap->second << endl;
    }
    m_map.insert(make_pair(
"Kobe Bryant"24));
    
//m_map["Kobe Bryant"] = 24;
    iteMap = m_map.begin();
    cout << 
"==============新值=============" << endl;
    
for(; iteMap != m_map.end(); ++ iteMap)
    {
        cout << iteMap->first;
        cout << 
":";
        cout << iteMap->second << endl;
    }
    
return 0;
}

  看了半天,似乎并没有把key为Kobe Bryant的value修改为24,还是之前的值8。通过insert操作修改map指定key的value是不行的,正确的做法是这样的:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
// mapmodifykey.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>

using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    map<string, 
int> m_map;
    m_map.insert(make_pair(
"Michael Jordan"23));
    m_map.insert(make_pair(
"Kobe Bryant"8));
    m_map.insert(make_pair(
"James Harden"13));
    m_map.insert(make_pair(
"Chris Paul"3));
    map<string, 
int>::const_iterator iteMap = m_map.begin();
    cout << 
"==============旧值=============" << endl;
    
for(; iteMap != m_map.end(); ++ iteMap)
    {
        cout << iteMap->first;
        cout << 
":";
        cout << iteMap->second << endl;
    }

    
//m_map.insert(make_pair("Kobe Bryant", 24));
    m_map["Kobe Bryant"] = 24;
    iteMap = m_map.begin();
    cout << 
"==============新值=============" << endl;
    
for(; iteMap != m_map.end(); ++ iteMap)
    {
        cout << iteMap->first;
        cout << 
":";
        cout << iteMap->second << endl;
    }
    
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值