当我尝试使用 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/