c++ - 为什么我的简单 map.find(x) 不起作用?

标签 c++ debugging dictionary insert find

当我尝试使用 find()map在我的 C++ 程序中,该函数似乎无法正常工作。

代码如下:

map 定义如下:

std::map<std::string,ownObject*> objects;

这是未运行的代码

void someClass::addTarget(std::string objectName, ownObject* object)
{
if (this->objects.find(objectName) != this->objects.end())
    this->objects.insert(std::pair<std::string,ownObject*>(objectName,object));
}

我的实际意图是检查是否已经存在具有该名称的条目(映射的第一个键),如果没有则将其添加到映射中。

现在由于某些原因,他从未进入 if 函数(调用 insert())。来自 http://msdn.microsoft.com/en-us/library/92cwhskb.aspx我得到了 find() 的返回值是正在寻找的元素 - 或者如果它不可用则为 objects.end()

调试时 map 对象已经包含<'a',anObject> ,然后我尝试添加 <'b',anotherObject> ,但正如我所说,他永远不会到达 insert()功能,我不明白为什么。

正如给定主页上的解释(实际上尝试了他们的 if-question),这实际上应该有效,所以不幸的是我什至不知道问题出在哪里。

有人有想法吗?

最佳答案

My actual intention is, to check, if there is already an entry with that name (first key of the map) and if not add it to the map.

那么你需要(==):

void someClass::addTarget(std::string objectName, ownObject* object)
{
if (this->objects.find(objectName) == this->objects.end())
    this->objects.insert(std::pair<std::string,ownObject*>(objectName,object));
}

std::map::find 将在范围内找不到键时返回 std::map::end。因此,您需要检查是否相等。

关于c++ - 为什么我的简单 map.find(x) 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24546188/

相关文章:

c++ - 一次写入多个文件

c++ - 如何调试在gdb中触发内部错误的C++程序?

c++ - 在 linux 上编译 windows 64 程序时出现问题 - headers

java - while 循环之外的 ArrayList 未更新

c - 什么?在 gdb backtrace 中意味着以及如何获得实际的堆栈帧?

python - 有条件地计算嵌套 python json 字典中值的数量

c# - 可以接受使用类型作为字典键吗?

c++ - (Winapi C++) 如何在没有全局变量的情况下将数据从一个窗口传递到另一个窗口?

java - 使用 Gson 在 Java 中对 HashMap<Int,Object> 进行序列化/反序列化

Python请求获取JSON