c++ - 比较两个指针以用于标准算法的正确方法

标签 c++ boost lambda

我正在使用 boost::range 和 boost::lambda 使用以下示例来比较两个数字并找出具有相同数字的元素。

#include <iostream> 
#include <boost/optional.hpp> 
#include <boost/range/algorithm/find_if.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/utility/compare_pointees.hpp>

template <class Range, class Predicate> 
boost::optional<typename boost::range_value<Range>::type> 
search_for(const Range& r, Predicate pred) 
{ 
      BOOST_AUTO (it, boost::find_if(r, pred));
      if (it == boost::end(r)) 
          return boost::none; 
      return *it; 
 } 


 int main() 
 { 
  int a = 1;
  int b = 2;
  int c = 3;
  int d = 3;

  std::vector<int*> m = {&a, &b, &c}; 
  if (boost::optional<int*> number = 
  search_for(m, boost::equal_pointees(???, &d))) { 
       std::cout << "found:" << (*number.get()) << std::endl; 
  } 
  else { 
       std::cout << "not found" << std::endl; 
   } 
}

我应该在 search_for 函数中为上面的 ??? 使用什么?

我相信这可能很简单,但不知道该怎么做。我可以使用 boost::bind 或 std::bind2d 等进行比较,但我在想是否有任何优雅的方法可以做到这一点。此外,此代码示例可以重组为更简单的代码示例,但我只是在学习。

最佳答案

使用 boost::lambda,它看起来像这样:

namespace ll = boost::lambda;

search_for(m, *ll::_1 == d)

这比获取指向 d 的指针要简单得多,这样您就可以使用 equal_pointees

关于c++ - 比较两个指针以用于标准算法的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253005/

相关文章:

java - 使用 Java 8 迭代二维数组

python - 在 boost.python 中使用它时不能在我的抽象类中使用纯虚函数

c++ - 用于将任意成员函数应用于对象容器容器的仿函数

c++ - Boost weak_ptr在多线程程序中实现资源池

c++ - 使用模板时什么时候应该使用关键字 "typename"

ruby-on-rails - Ruby lambda 执行与规范中的 should

java - 如何根据 Java 8 Stream 过滤器的输出计算百分比

c++ - Boost 版本在 Ubuntu Trusty 上至少为 1.56

c++ - 链表增加节点数

c++ - 如何将 unsigned char 数组转换为 unsigned long long?