std::map 发现在 C++ 中不起作用
std::map find not working in C++
我使用以下几行创建了一个哈希映射和一个迭代器:
std::map<const char*,vaLueClass *> myCache;
std::map<const char*,vaLueClass *>::iterator myCacheIterator;
然后我使用下面的行插入到这张地图中:
myCache[anotherObject->getStringKey()] = new vaLueClass(anotherObj1->getIntAttr(), anotherObj1-->getIntAttr());
然后,每当我尝试使用下面的行搜索此映射或螺母中是否存在特定字符串的条目时,它总是进入 IF 块,换句话说,它确实在此地图中找不到任何条目。
myCacheIterator= myCache.find(sampleObject->getstringKey());
注意:此处 sampleObject->getstringKey()
returns 之前插入的相同密钥。
if (myCacheIterator.operator ==(myCache.end())){
// this block means that no matched entry is found inside the map myCache
}
此外,这是在 C++ 中创建和使用 std::map 的正确方法吗?如果没有,请推荐一个。
此外,我还没有使用关键字 new
来创建 std::map 对象。
在 std::map
中,执行搜索时使用小于 operator <
比较键。由于您将 const char*
作为键存储,这意味着查找将比较指针本身而不是它们指向的字符串,因此如果您不传递用于插入地图的确切指针,查找将找不到任何内容。
我认为这里最简单的解决方法是使用 std::strings
作为键,因为 std::string
上的 <
运算符实际上比较基础文本。那应该很快就能解决您的问题。
您可以有多种选择来解决这个问题:
1) 您可以使用 std::string 而不是 const char *
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
2) Map声明见上。第三个模板参数是比较函子。您可以将自定义仿函数传递给地图以实现正确的行为。
3) std::less 使用 operator< 。你可以写 operator< for const char * .
我使用以下几行创建了一个哈希映射和一个迭代器:
std::map<const char*,vaLueClass *> myCache;
std::map<const char*,vaLueClass *>::iterator myCacheIterator;
然后我使用下面的行插入到这张地图中:
myCache[anotherObject->getStringKey()] = new vaLueClass(anotherObj1->getIntAttr(), anotherObj1-->getIntAttr());
然后,每当我尝试使用下面的行搜索此映射或螺母中是否存在特定字符串的条目时,它总是进入 IF 块,换句话说,它确实在此地图中找不到任何条目。
myCacheIterator= myCache.find(sampleObject->getstringKey());
注意:此处 sampleObject->getstringKey()
returns 之前插入的相同密钥。
if (myCacheIterator.operator ==(myCache.end())){
// this block means that no matched entry is found inside the map myCache
}
此外,这是在 C++ 中创建和使用 std::map 的正确方法吗?如果没有,请推荐一个。
此外,我还没有使用关键字 new
来创建 std::map 对象。
在 std::map
中,执行搜索时使用小于 operator <
比较键。由于您将 const char*
作为键存储,这意味着查找将比较指针本身而不是它们指向的字符串,因此如果您不传递用于插入地图的确切指针,查找将找不到任何内容。
我认为这里最简单的解决方法是使用 std::strings
作为键,因为 std::string
上的 <
运算符实际上比较基础文本。那应该很快就能解决您的问题。
您可以有多种选择来解决这个问题:
1) 您可以使用 std::string 而不是 const char *
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std::allocator<std::pair<const Key, T> >
> class map;
2) Map声明见上。第三个模板参数是比较函子。您可以将自定义仿函数传递给地图以实现正确的行为。
3) std::less 使用 operator< 。你可以写 operator< for const char * .