简体   繁体   English

如果只定义了一个小于比较器,upper_bound() 是如何工作的?

[英]How does upper_bound() work if only a less-than comparator is defined?

I was given a class that is built on top of a map with the following K type and V type limitations:我得到了一个 class,它建立在 map 之上,具有以下 K 类型和 V 类型限制:

  • K : copyable, assignable, is less-than comparable ( < ). K :可复制,可分配,小于可比性 ( < )。 Does not implement any other operations (no equality comparison or arithmetic operators)不实现任何其他操作(无相等比较或算术运算符)

  • V : copyable, assignable, equality-comparable ( == ). V :可复制、可赋值、相等可比较 ( == )。 Does not implement any other operations.不执行任何其他操作。

Given that limitation, wouldn't this code not work?鉴于该限制,这段代码不会起作用吗?

auto it = map.upper_bound(K);

Since upper_bound() (as defined here ) returns an iterator pointing to the first element that is greater than key.由于upper_bound() (定义为此处)返回指向第一个大于键的元素的迭代器。 Meaning the K would use a greater-than comparator?意思是 K 会使用大于比较器?

Or does it follow that a definition of a less-than comparator would also define a greater-than comparator?或者是否遵循小于比较器的定义也将定义大于比较器?

Or is my understanding of how upper_bound() works wrong?还是我对upper_bound()工作原理的理解有误?

As commented by @Nate Eldredge:正如@Nate Eldredge 评论的那样:

I believe you would get the first element y such that key < y.我相信你会得到第一个元素 y 这样 key < y。 That's what "greater than" means in this context.这就是“大于”在这种情况下的意思。 Not the first y such that y > key不是第一个 y y > key

and from C++ documentation of upper_bound() :以及来自upper_bound() 的 C++ 文档

template <class ForwardIterator, class T>
ForwardIterator upper_bound (ForwardIterator first, ForwardIterator last, const T& val)
{
 ForwardIterator it;
 iterator_traits<ForwardIterator>::difference_type count, step;
 count = std::distance(first,last);
 while (count>0)
{
    it = first; step=count/2; std::advance (it,step);
    if (!(val<*it))                 // or: if (!comp(val,*it)), for version (2)
      { first=++it; count-=step+1;  }
    else count=step;
  }
  return first;
}

upper_bound() uses a < operator for comparison or to be more specific this: !(val<*it) upper_bound() 使用<运算符进行比较或更具体地说: !(val<*it)

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

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