【发布时间】:2013-01-10 07:55:39
【问题描述】:
我已将自定义类型“MyType”包装在智能指针中:
tr1::shared_ptr<MyType>
并从中制作了一个向量:
vector<shared_ptr<MyType>>
现在我想在该向量中 std::find 一个 MyType 类型的对象,但不能因为我需要的类型是 shared_ptr<MyType>。
有没有优雅的方法? 谢谢
更新:为什么不使用 std::find_if:std::find 的用法非常紧凑。我认为为 find_if 实现方法或函子的开销太大。
【问题讨论】:
-
您可以为 shared_ptr
定义运算符“==”,但唯一不污染代码的优雅方法是使用 find_if -
唯一的办法就是使用find_if。从这里引用 (en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp) -
Note that the comparison operators for shared_ptr simply compare pointer values; the actual objects pointed to are not compared. -
使用标准库的方法是使用
find_if。什么不能用? -
对不起;我真的希望你解释一下为什么你不想使用
find_if。因为这是正确的解决方案,所以把那句话扔出去是没有帮助的。 -
@BenjaminLindley 异构比较运算符是维护的噩梦,因为您还想要普通比较的左右对称,并且您必须担心隐式转换等。
标签: c++ boost stl find shared-ptr