C++集查找值较小但更接近x

C++ set find value smaller but closer to x

本文关键字:接近 查找 C++      更新时间:2023-10-16

我查看了<set>的C++STL中的lower_boundupper_bound。然而,我找不到一种方法来获得与集合中另一个值最接近的值(从下面开始)。有没有一种简单的方法可以得到它,或者我必须迭代集合?

举个例子,假设我的集合包含以下整数3 4 7 9,然后是closest(6) = 4closest(4) = 4

std::upper_bound返回一个大于给定值的元素,因此在您的情况下,您必须将其递减才能获得之前的值。

//Returns value of element before 'num'
int closest = *--set.upper_bound(num);

我本以为是closest(6) = 7,因为74更接近6。如果要获得7,则必须计算相邻值之间的差异并进行比较。

//Calculate closest value to 'num' in a std::set<int>
int closest(std::set<int>& set, int num)
{
    //Get iterator to element greater than 'num'
    auto it = set.upper_bound(num);
    //Check if 'it' is the 'end' iterator
    if (it == std::end(set))
        return 0;
    int valueLeft = *it--; //Get value of the greater element
    int valueRight = *it; //Get value of the element before (due to post-decrement)
    //Compare diffence between value less and num, and value greater and num
    if (valueLeft - num > num - valueRight)
        return valueRight;
    else
        return valueLeft;
}
std::set<int> set{ 3, 4, 7, 9 };
int a = closest(set, 6); //Returns '7'
int b = closest(set, 4); //Returns '4'

试试这个通用算法:

template <typename Set>
typename Set::const_iterator
find_closest(Set const & s, typename Set::value_type const & val)
{
    auto a = s.begin(), b = s.end(), it = s.lower_bound(val);
    if (it == b) 
    {
        if (it != a) --it;
        return it;
    }
    auto nt = std::next(it);
    if (nt == b) return it;
    return val - *it < *nt - val ? it : nt;
}
//included all libraries
 auto find(int l, set<int>&s){
     auto it=s.lower_bound(l);  
   
     if(s.size() and *s.begin()<=l){ //check any smaller element present in set
        
        auto it=s.upper_bound(l);
             it=prev(it);
     }   
   return it;
}