0

cpprefernce说:

template< class ForwardIt, class T, class Compare > ForwardIt
upper_bound( ForwardIt first, ForwardIt last, const T& value, compare comp );

(...)

comp​true-如果第一个参数小于第二个参数,则 返回比较函数对象(即满足比较要求的对象) 。比较函数的签名应该等同于以下内容:

bool cmp(const Type1 &a, const Type2 &b);

(...) 类型Type1必须使得类型的对象T可以隐式转换为Type1. 类型Type2必须是ForwardIt可以取消引用类型的对象,然后隐式转换为Type2.

具有以下代码:

#include <algorithm>
#include <string>
#include <vector>

using namespace std;

struct employee {
  string first;
  string last;
};

int main() {
  vector<employee> v = { {"John", "Smith"} };

  sort(v.begin(), v.end(),
       [](const employee& e1, const employee& e2) { return e1.last < e2.last; });

  auto p = lower_bound(v.begin(), v.end(), "Smith",
                       [](const employee& e, const string& y) { return e.last < y; });
}

以及 cppreference 的可能实现

template<class ForwardIt, class T, class Compare>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value, Compare comp)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first,last);

    while (count > 0) {
        it = first; 
        step = count / 2;
        std::advance(it, step);
        if (!comp(value, *it)) {
            first = ++it;
            count -= step + 1;
        } else count = step;
    }
    return first;
}

传递给 ' 调用的 lambda 中的参数顺序lower_bound应该颠倒,因为它value是 aconst std::string&并且它comp作为第一个参数传递给,但它像这样编译,如果传递不同,则会产生编译错误。

我在这里想念什么?

4

0 回答 0