地图插入密钥,但没有值
map inserting keys but not value
我今天正在使用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;
然后它将起作用。
相关文章:
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 允许从 std::map 的密钥窃取资源?
- TMap::Emplace() 在应用现有密钥时会覆盖吗?
- 在没有密钥的情况下读取密文的剩余噪声预算
- 如何修复无效的API密钥,IP或操作权限错误?
- 所有可能的链接生成器与64位密钥
- 如何在unordered_map中更改密钥?
- 获取当前密钥状态?
- curl_easy_perform() 失败:SSL 对等证书或 SSH 远程密钥不正常
- 将密钥发送到非前台的游戏窗口
- 有哪些方法可以对基于 256 位密钥的矩阵进行加扰?
- 如何在精灵表上的两个不同部分之间来回切换,同时用户仍使用 SFML 持有密钥
- 如何将CNG密钥转换为OpenSSL EVP_PKEY(反之亦然)?
- 运行密钥密码解密知道密钥?
- std::unordered_map 运算符 [] 是否对非现有密钥进行零初始化?
- 封装 std::map 以允许迭代,但没有直接密钥访问?
- 地图插入密钥,但没有值
- 如何处理插入现有密钥
- std::map:插入密钥后,它是否可以复制和移动密钥
- C++:在不知道密钥的情况下插入std::map