地图插入密钥,但没有值

map inserting keys but not value

本文关键字:插入 密钥 地图      更新时间:2023-10-16

我今天正在使用C 代码。了解性病容器。我正在尝试在std ::映射中插入和更新数据,但是由于某些原因,我无法将值插入地图中。键将插入但不值得值。如果您输入打开的终端,则底部的代码将打印以下内容。在此示例中,我输入了"测试"。无论如何,我的问题是,为什么插入物返回错误,为什么在值不插入的值中?

test 
first 
failed 
Context1 : 

这是代码:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <map>
#include <random>
static std::map<std::string, std::string> currentFullState;
static const std::string sDEFAULT_STRING = "";
void PringCurrentState()
{
    std::map<std::string, std::string>::iterator stateData = currentFullState.begin();
    while (stateData != currentFullState.end())
    {
        std::cout << stateData->first << " : ";
        std::cout << stateData->second << std::endl;
        stateData++;
    };
}
void UpdateState(std::string context, std::string data)
{
    if (currentFullState[context] == sDEFAULT_STRING)
    {
        // first entry, possibly special?
        std::cout << "first" << std::endl;
        auto result = currentFullState.insert(std::make_pair(context, data.c_str()));
        if (result.second == false)
            std::cout << "failed" << std::endl;
        else
            std::cout << "good" << std::endl;
    }
    else if (data != currentFullState[context])
    {
        // change in value
    }
    else
    {
        currentFullState[context] == data;
    }
}
void DoWork()
{
    if (rand() % 2)
    {
        UpdateState("Context1", "Data1");
    }
    else
    {
        UpdateState("Context2", "Data2");
    }
}
int main()
{
    std::string command = "";
    for (;;)
    {
        PringCurrentState();
        std::cin >> command;
        DoWork();
        if (command == "q")
        {
            break;
        }
    }
    return 0;
}

为什么插入不起作用?

肯定会有所帮助,如果您写了

currentFullState[context] = data;

而不是

currentFullState[context] == data;

auto result = currentFullState.insert(std::make_pair(context, data));

应优先于

auto result = currentFullState.insert(std::make_pair(context, data.c_str()));

第二个汇编的人有些惊讶。

==================================================================================

插入失败的真正原因是您第二次添加该键。这是第一次

if (currentFullState[context] == sDEFAULT_STRING)

operator[]在地图上始终将密钥添加到地图中。这就是为什么您第二次尝试添加

的原因
auto result = currentFullState.insert(std::make_pair(context, data.c_str()));

失败,键已经存在。如果您写了

currentFullState[context] = data;

然后它将起作用。