我今天在玩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/