我正在使用 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/