2012-01-26 75 views
0

假设我想在一个std使用std :: LOWER_BOUND ::指针的载体是这样的:的boost ::绑定或升压::性病拉姆达:: LOWER_BOUND

struct X { 
    int x; 
    double y; 
}; 

// overloads for normal comparisons 
bool operator< (int left, const X& right) { return left < right.x; } 
bool operator< (const X& left, int right) { return left.x < right; } 

std::vector<X*> v; 

int searchValue = 5; 
std::vector<X*>::iterator it = std::lower_bound(v.begin(), v.end(), searchValue, 
    ? // what the heck do I put here? 
); 

我会使用boost ::绑定或提升:: lambda在这里,如果是这样,如何?

我认为这将是这样的:

std::lower_bound(v.begin(), v.end(), searchValue, searchValue < *_1); 

但是我在这得到一个非法间接错误。

+0

Boost.Lambda因为[Boost.Phoenix(http://www.boost.org/libs/phoenix/)V3的发布正式弃用,所以_real_答案是使用Boost.Phoenix。也就是说,你使用Boost.Phoenix的代码没有任何改变(除了'operator <'的参数是反向的)。 – ildjarn

+0

通常我会说'std :: less ()',但是你将'int'与'X'进行比较,这样就无法工作。 – Flexo

+0

不幸的是,我仍然在提升1.43,所以Boost.Phoenix不可用:( – syvex

回答

0

经过一些试验和错误后得到它。 Boost.Bind在这里不起作用,并且编译器会因使用占位符而感到困惑。 Boost.Bind在匿名根名称空间中使用_1。 Boost.Lambda在名称空间boost :: lambda :: _ 1下使用它。

此外,我的命令与比较错误。

#include <boost/lambda/lambda.hpp> 

// ... 

std::vector<X*>::iterator it = std::lower_bound(v.begin(), v.end(), searchValue, 
    *boost::lambda::_1 < searchValue 
); 
+0

但是,VS 2008会在您将X *更改为boost :: shared_ptr 时抱怨。不知道这是怎么回事。 VS 2010工作正常。 – syvex

0

请尝试以下

struct MyLessThan 
{ 
    bool operator()(const X* xVal, int iVal) 
    { 
     return xVal->x < iVal; 
    } 
}; 

std::vector<X*> v; 

int searchValue = 5; 
std::vector<X*>::iterator it = std::lower_bound(v.begin(), v.end(), searchValue, MyLessThan()); 

这应该工作。

+0

不需要,因为std :: vector存储指针,所以需要指向operator()的指针参数 – Xeo

+0

@Xeo :)我没有注意到它是一个指针向量,它也有另一个错误,谢谢你的更正 – broc

+0

这会起作用,但我希望避免定义一个自定义谓词。使用boost :: bind或lambdas。 – syvex