簡體   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