繁体   English   中英

下限上限给出相同的结果

[英]lower bound upper bound giving same results

我正在尝试在排序数组中找到最接近的值,但是upper_bound和lower_bound都给出了最大值。

float abc[] = {1,3,4,5,6,7,8,9};

float *a  = lower_bound(abc, abc+8, 3.2);
cout<< *a;

return 0;

*a在两种情况下*a均为4,因为如果a所指向的值正确插入容器中,则其值为3.2

如果在容器中不存在传递的值,则lower_boundupper_bound将返回相同的迭代器。

lower_bound返回的迭代器被定义为传递的元素可以位于容器中的最低位置, higher_bound返回的最高位置。 它们返回与数组中存在的最接近元素有关的任何内容。

为了找到最接近的元素,您知道lower_bound的取消引用结果大于或等于传递的值。 之前的值(如果有)必须小于。 您可以利用它来获得最接近的值。

由于数组中不存在值3.2,因此两种算法std::lower_boundstd::upper_bound将返回相同的迭代器。

在这种情况下,您应该考虑使用以前的迭代器。

这是一个演示程序。

#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstdlib>

int main() 
{
    float abc[] = { 1, 3, 4, 5, 6, 7, 8, 9 };
    float value = 3.2f;

    auto it = std::lower_bound( std::begin( abc ), std::end( abc ), value );

    auto closest = it;

    if ( it == std::end( abc ) )
    {
        closest = std::prev( it );
    }
    else if ( it != std::begin( abc ) )
    {
        closest = std::min( std::prev( it ), it, 
                            [&value]( const auto &p1, const auto &p2 )
                            {
                                return abs( value - *p1 ) < abs( value - *p2 );
                            } );
    }

    std::cout << *closest << " at position " << std::distance( std::begin( abc ), closest ) << std::endl;
    return 0;
}

它的输出是

3 at position 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM