2010-02-25 60 views
0

结合equal_range我使用与bind2nd和binary_function

class MultiValuedComparator 
{ 
public: 
    item a; 
    item b; 

    MultiValuedComparator(item c, item d) 
    { 
     a = c; 
     b = d; 
    } 
}; 

因为我有项的副本的

class Thing 
{ 
public: 
    item a; 
    item b; 
    other data; 
}; 

vector<Thing> Things; 

一个有序集合,项目B(而不是其他的数据),我想获取匹配项目a和项目b的那些数据结构的范围。该集合仅按项目a排序。

我以为equal_range是一个合适的方法来做到这一点。因为我需要匹配从binary_function继承的多个项目。

struct RangeByA : public std::binary_function<Thing, MultiValuedComparator> 
{ 
    bool operator()(const Thing &left, const MultiValuedComparator &right) 
    { 
     return left.a == right.a && left.b == right.b; 
    } 
} 

我不知道如何编写equal_range函数,所以它这样做。我想:

void somefunction() 
{ 
    typedef pair<vector<Thing>::iterator, 
       vector<Thing>::iterator> startEndIterPair; 

    MultiValuedComparator mvc(1, 2); 

    startEndIterPair p = equal_range 
     (
     Things.start(), 
     Things.end(), 
     std::bind2nd(RangeByA, mvc) 
    ); 
} 

但是这个代码不抱怨比赛为“运营商<”在“__middle .__ gnu_cxx :: __ normal_iterator ..等在调用equal_range

我怎样写这个如此equal_range会工作?我不知道在哪里放置重载的操作符。 RangeByA似乎不接受它。

+0

什么MultiValuedComparator做(或u想要它做)? – YeenFei 2010-02-25 02:49:12

+0

YeenFei:它只是包含我想要在向量中搜索的值,作为我的函子的一部分。 – jjacksonRIAB 2010-02-25 03:24:48

+0

它似乎没有引起问题,但它应该是'std :: binary_function '。 'binary_function'需要三个模板参数。 – 2010-02-25 06:05:41

回答

0

对于equal_range的比较器的要求是严格的弱排序(不等于)。此外,比较器必须能够在这两个命令的参数来调用:

comparator(*iter, value); // items less than lower bound 
comparator(value, *iter); // items greater than upper bound 

equal_range的结果,那么,是迭代器的范围,其中这两个调用的返回false

一个简单的调整,那么,是一个构造添加到MultiValuedComparator接受的事情,允许Thing对象转换为一个MultiValuedComparator对象进行比较:

class MultiValuedComparator 
{ 
public: 
    item a; 
    item b; 

    MultiValuedComparator(item c, item d) 
    { 
     a = c; 
     b = d; 
    } 

    MultiValuedComparator(const Thing &thing) 
    { 
     a = thing.a 
     b = thing.b 
    } 
}; 

,然后调整比较器,用于只使用MultiValuedComparator和使用严格弱序:

struct RangeByA : public std::binary_function<MultiValuedComparator, MultiValuedComparator> 
{ 
    bool operator()(const MultiValuedComparator &left, const MultiValuedComparator &right) 
    { 
     // Sorted by a first, then b if necessary 
     return (left.a < right.a) 
       || (!(right.a < left.a) && (left.b < right.b))); 
    } 
}; 

上述之外,这将避免副本(从事MultiValuedComparator),是一种替代简单地实现operator()在两个直销行动(的事对MultiValuedComparator和MultiValuedComparator与事),下降的std::binary_function继承(这里没有必要):

struct RangeByA 
{ 
    bool operator()(const Thing &left, const MultiValuedComparator &right) { 
     // ... (same body as above) 
    } 

    bool operator()(const MultiValuedComparator &left, const Thing &right) { 
     // ... (same body as above) 
    } 
};