【问题标题】:Find elements in a vector of tr1::shared_ptr在 tr1::shared_ptr 的向量中查找元素
【发布时间】:2013-01-10 07:55:39
【问题描述】:

我已将自定义类型“MyType”包装在智能指针中:

tr1::shared_ptr<MyType>

并从中制作了一个向量:

vector<shared_ptr<MyType>>

现在我想在该向量中 std::find 一个 MyType 类型的对象,但不能因为我需要的类型是 shared_ptr&lt;MyType&gt;

有没有优雅的方法? 谢谢

更新:为什么不使用 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


【解决方案1】:

做你想做的事的惯用和优雅的方式是:

std::vector<std::shared_ptr<MyType>> v;

// init v here;

MyType my_value;

// init my_value here;

auto it = std::find_if(v.begin(), v.end(), [&](std::shared_ptr<MyType> const& p) {
    return *p == my_value; // assumes MyType has operator==
});

if (it != v.end()) { /* do what you want with the value found */ }

如果您可以使用std::vectorstd:shared_ptr,那么您显然已经在使用STL。那么为什么不使用std::find_if呢?如果你不能使用 C++11 的 lambda 表达式,你总是可以使用函数对象。

【讨论】:

  • 酷,谢谢,这很有帮助。不知道我可以使用 lambda 表达式。为 dont-want-find_if 评论感到抱歉。我不想使用 find_if,因为在我看来,编写比较方法/仿函数不会比自己查找值更紧凑。但是您的解决方案有效,并且确实是我想要的。
【解决方案2】:

只回答您发布的问题,忽略您对 find_if 的厌恶:

std::vector<std::shared_ptr<MyType>> myVector; 
/* ... */
MyType const& whatIAmlookingFor = /* ... */;
auto ptr = std::find_if(begin(myVector), end(myVector), [&](std::shared_ptr<MyType> const& current)
{
  return *current == whatIAmLookingFor;
});

现在关于您不想使用 find_if “出于某些原因”(可能是什么原因?): 您正在寻找一种优雅的 STL/boost 方式来做某事,但不想使用优雅的 STL 方式来做某事?听起来不对。

【讨论】:

    猜你喜欢
    • 2013-09-07
    • 2010-10-03
    • 2020-11-19
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 2018-11-26
    相关资源
    最近更新 更多