c++ - 下限 == 上限

标签 c++ math stl naming-conventions

lower_bound 是什么意思。如果我不得不猜测,我会回答这个函数在小于请求值的最后一个元素处返回迭代器。但我看到lower_bound 几乎和upper_bound 一样。唯一的区别是在 upper_bound 的情况下严格不等式。 STL中是否有真正的下限选择函数与下限的正常定义一致。

编辑:文档中有太多的否定让我感到困惑。问题是我得到了相同的迭代器。我通过从 lower_bound 返回值中减去 1 来解决它。我用它来插值:

    float operator()(double f)
        {
        SpectrumPoint* l=std::lower_bound(beginGet(),endGet(),(SpectrumPoint){float(f),0.0f}
            ,SpectrumPoint::CompareFreqLessThan);
        if(l>beginGet())
            {--l;}

        SpectrumPoint* u=std::lower_bound(beginGet(),endGet(),(SpectrumPoint){float(f),0.0f}
            ,SpectrumPoint::CompareFreqLessThan);

        if(u==endGet())
            {u=beginGet();}

        if(l==u)
            {
            if(u==endGet())
                {return u->amp;}
            return l->amp;
            }

        double f_min=l->freq;
        double A_min=l->amp;
        double f_max=u->freq;
        double A_max=u->amp;

        double delta_f=f_max-f_min;
        double delta_A=A_max-A_min;

        return A_min + delta_A*(f-f_min)/delta_f;
        }

我很抱歉造成这种困惑:-(

最佳答案

  • 下限:第一个大于或等于的元素。

  • 上限:严格大于的第一个元素。

示例:

+- lb(2) == ub(2)       +- lb(6)        +- lb(8)
|        == begin()     |  == ub(6)     |   +- ub(8) == end()
V                       V               V   V
+---+---+---+---+---+---+---+---+---+---+---+
| 3 | 4 | 4 | 4 | 4 | 5 | 7 | 7 | 7 | 7 | 8 |
+---+---+---+---+---+---+---+---+---+---+---+
    ^               ^                       ^
    |               |                       |
    +- lb(4)        +- ub(4)                +- lb(9) == ub(9) == end()

    |- eq-range(4) -|

如您所见,n 的半开等距是 [lb(n), ub(n)) .

请注意,这两个边界都为您提供了所需值元素的有意义的插入位置,以便保持顺序,但 lower_bound 具有 if 元素的显着特征已经存在,那么您将获得一个实际上指向该元素的迭代器。因此,您可以在有序范围上使用 lower_bound 来实现您自己的唯一成员身份多成员身份容器。

void insert(Container & c, T const & t)
{
    auto it = std::lower_bound(c.begin(), c.end(), t);

    // if unique container:
    if (it != c.end() && *it == t) { /* error, element exists! */ return; }

    c.insert(it, t);
}

关于c++ - 下限 == 上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12158948/

相关文章:

c++ - libpng 警告 : Incompatible libpng version in application and library

c++ - 测试对象是否被删除

C++ std::vector 内存/分配

java - 我的java代码在线程 "main"java.lang.ArrayIndexOutOfBoundsException中抛出异常?

java - 用Java制作轮盘赌风格的Poly Wheel

c++ - 在容器中查找以给定字符开头的所有单词

c++ - 如何在 C++ 中将 hash_map 用于字符串键和 int 值

派生类上的 C++ 赋值运算符实现

c++ - 来自 C++ 的 Lua 回调

sql - 选择 sum where 子句 SQL