如何在包含指向元素的指针的集合中找到一个元素? [英] How can I find an element in a set which contains pointers to the elements?
问题描述
:我更正了一个错误:我使用的是set
而不是vector
.
I fixed my mistake: I'm using a set
and not a vector
.
请考虑以下示例代码:
set<Foo *> set_of_foos;
set_of_foos.insert(new Foo(new Bar("x")));
set_of_foos.insert(new Foo(new Bar("y")));
[...]
// The way a "foo" is found is not important for the example.
bool find_foo(Foo *foo) {
return set_of_foos.end() != set_of_foos.find(foo);
}
现在我打电话给
find_foo(new Foo(new Bar("x")));
该函数返回false
,因为找不到我要查找的内容.对我来说,原因很明显:指针指向不同的对象,因为它们都被分配了new
,从而导致地址的值不同.
the function returns false
since what I'm looking for can't be found. The reason is obvious to me: The pointers point to different objects since they are allocated both with a new
, resulting in different values of the addresses.
但是我想比较Foo
的内容(即上例中的"x"
)而不是Foo *
本身.除了修改Foo
之外,不能使用Boost.
But I want to compare the contents of Foo
(i.e. "x"
in the above example) and not Foo *
itself. Using Boost is not an option as well as modifying Foo
.
我是否需要遍历set_of_foos
内部的每个Foo *
,还是有一个更简单的解决方案?我尝试对每个Foo
的内容进行唯一的序列化,然后将set<Foo *>
替换为map<string, Foo *>
,但这似乎是一个非常"hacked"的解决方案,效率不高.
Do I need to loop through each of the Foo *
inside set_of_foos
or is there a simpler solution? I tried uniquely serializing the contents of each Foo
and replace the set<Foo *>
with a map<string, Foo *>
, but this seems like a very "hacked" solution and not very efficient.
推荐答案
find_foo(new Foo(new Bar("x")));
听起来不是个好主意-在任何情况下,该搜索功能很可能导致内存泄漏.
find_foo(new Foo(new Bar("x")));
does not sound like a good idea - it will most likely (in any scenario) lead to memory leak with that search function.
您可以将find_if与函子一起使用:
You could use find_if with a functor:
struct comparator {
Foo* local;
comparator(Foo* local_): local(local_) {}
~comparator() { /* do delete if needed */ }
bool operator()(const Foo* other) { /* compare local with other */ }
};
bool found = vec.end() != std::find_if(vec.begin(), vec.end(), comparator(new Foo(...)));
这篇关于如何在包含指向元素的指针的集合中找到一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!