c++ - 映射插入键但不插入值

标签 c++ std stdmap

我今天在玩c++代码。了解标准容器。我正在尝试在 std::map 中插入和更新数据,但由于某种原因我无法将值插入到 map 中。键将插入但不插入值。如果您在打开的终端中输入内容,底部的代码将打印以下内容。在这个例子中,我输入了“测试”。无论如何,我的问题是,为什么插入返回 false,为什么不插入值?

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)
map 上的

operator[] 总是 将键添加到 map 。这就是为什么您第二次尝试添加

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

失败, key 已经存在。如果你写了

currentFullState[context] = data;

然后它就可以工作了。

关于c++ - 映射插入键但不插入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48718914/

相关文章:

c++ - 链表中的指针

c++ - 使用数据库模型(键)来引用运行时对象,好主意还是坏主意?

c++ - 向右移动4个整数不同的值SIMD

c++ - 自定义池分配器 std::list

c++ - 是否可以将默认构造函数设置为 `std::map<T1, T2>` 值?

C++ 类型列表及其在列表中的别名

c++ - 错误 : 'shuffle' is not a member of 'std'

c++ - 两个单独的键映射到 std::map 中的单个条目

c++ - 使用 SFML 处理多个客户端套接字

c++ - map中operator[]插入的指针类型的值是否总是NULL?