对于UPPER_BOUND / LOWER_BOUND比较功能 [英] compare function for upper_bound / lower_bound

查看:374
本文介绍了对于UPPER_BOUND / LOWER_BOUND比较功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到有比一些x值的字段少的排序向量的第一个项目。
我需要提供比较函数比较'X'在MyClass的内在价值,但我不能工作了函数声明。
不能我只是重载'<但我怎么做到这一点的args是当'和; MyClass的和浮动

 浮动X;
 的std ::矢量< MyClass的>:迭代最后=的std :: UPPER_BOUND(myClass.begin(),myClass.end(),X);
 

解决方案

您传递给排序算法什么功能也?你应该能够使用同一个用于UPPER_BOUND和LOWER_BOUND

做的比较工作的最简单的方法是用钥匙字段设置为您的搜索值创建一个虚拟对象。然后该比较将总是像对象之间的

编辑:如果由于某种原因,你无法获得与适当的比较值的虚拟对象,那么你就可以创建一个比较仿函数。该函子可以提供三种重载运算符():

 结构MyClassLessThan
{
    布尔运算符()(常量MyClass的&放大器;左,常量MyClass的&放大器;右)
    {
        返回left.key< right.key;
    }
    布尔运算符()(常量MyClass的&放大器;左,右浮动)
    {
        返回left.key<对;
    }
    布尔运算符()(左浮动,常量MyClass的&放大器;右)
    {
        返回左< right.key;
    }
};
 

正如你所看到的,那是很长的路要走呢。

I want to find the first item in a sorted vector that has a field less than some value x.
I need to supply a compare function that compares 'x' with the internal value in MyClass but I can't work out the function declaration.
Can't I simply overload '<' but how do I do this when the args are '&MyClass' and 'float' ?

 float x;
 std::vector< MyClass >::iterator last = std::upper_bound(myClass.begin(),myClass.end(),x);

解决方案

What function did you pass to the sort algorithm? You should be able to use the same one for upper_bound and lower_bound.

The easiest way to make the comparison work is to create a dummy object with the key field set to your search value. Then the comparison will always be between like objects.

Edit: If for some reason you can't obtain a dummy object with the proper comparison value, then you can create a comparison functor. The functor can provide three overloads for operator() :

struct MyClassLessThan
{
    bool operator() (const MyClass & left, const MyClass & right)
    {
        return left.key < right.key;
    }
    bool operator() (const MyClass & left, float right)
    {
        return left.key < right;
    }
    bool operator() (float left, const MyClass & right)
    {
        return left < right.key;
    }
};

As you can see, that's the long way to go about it.

这篇关于对于UPPER_BOUND / LOWER_BOUND比较功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆