使用const参数调用map :: find [英] Calling map::find with a const argument
问题描述
我有一个对象:
map<A*, string> collection;
我想调用map :: find函数, const,像下面的代码,它不编译:
I would like to call the map::find function, but the value I have for the key is const, like in the following code, which does not compile:
const A* a = whatever();
collection.find(a);
以下代码的工作原理与find操作相同:
The following code works and performs the equivalent of the find operation:
const A* a = whatever();
map<A*, string>::iterator iter;
for(iter = collection.begin(); iter != collection.end(); ++iter)
if(iter->first == a)
break;
// iter now contains the result or map::end (just like map::find)
但是它可能不如find成员函数那么有效,它也很丑陋,掩盖了代码的意图。
But it is probably not as efficient as the find member function, and it's also ugly and masks the intent of the code.
如何调用find函数?
How can I call the find function?
感谢
编辑:
我有意使用地图中的键的指针类型。我想要的行为是为地图使用指针相等的键。 (就像在我的循环代码)
I am intentionally using a pointer type for the key in the map. The behaviour I want is for the map to use pointer equality for the keys. (Just like in my loop code)
推荐答案
比较指针与它无关。 OP可以或可以不需要定制比较操作;它看起来对我来说,他们只是寻找一个特定的对象的地址,这似乎完全合理。
Comparing pointers has nothing to do with it. The OP may or may not need a custom compare operation; it looks to me like they're just looking for a specific object by its address, which seems perfectly reasonable. The first two answers seem to have missed the point that find() doesn't compile while a handwritten search works.
find()调用将无法编译,因为你可以使用find 're传递它错误的类型搜索。 map :: find()期望其参数与地图的键类型(即A *)具有相同的类型。你传递一个const A *,这不是隐式转换为A *(但是可以与A *相比,这就是为什么手写搜索工作)。隐式转换只适用于其他方向(A *到const A *,而不是const A *到A *)。
The find() call won't compile because you're passing it the wrong type to search for. map::find() expects its argument to be the same type as the map's key type, which is A*. You're passing a const A*, which is not implicitly convertible to an A* (but is comparable to an A*, which is why the handwritten search works). The implicit conversion only works in the other direction (A* to const A*, not const A* to A*).
可能你应该使用const A *的A *作为映射关键字;根据你使用的地图,这可能是也可能不实用。如果您需要地图键为A *,您需要传递一个A * to find(),这意味着从A *作为您的搜索目标开始,或者如果您只能从它的原始源作为const A *,使用find(const_cast (a))将其变成指向非const的指针(这与非常量指针不同,该指针混淆了很多C / C ++编码器)。通常const_cast是不合适的,但在这里它是安全的,因为你只是比较指针,不解除引用。
Possibly you should be using const A* instead of A* as the map key; depending on what you're using the map for, this may or may not be practical. If you need the map key to be A*, you need to pass an A* to find(), which means either starting with an A* as your search target in the first place, or if you can only get it from its original source as a const A*, using find(const_cast<A*>(a)) to turn it into a pointer to non-const (which is not the same as a non-const pointer, a point that confuses a lot of C/C++ coders). Usually const_cast is inadvisable, but here it's safe since you're only comparing the pointer, not dereferencing it.
这篇关于使用const参数调用map :: find的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!