cppreference言います:
template< class ForwardIt, class T, class Compare > ForwardIt upper_bound( ForwardIt first, ForwardIt last, const T& value, compare comp );(...)
comptrue-最初の引数が 2 番目の引数より小さい場合に 返される比較関数オブジェクト (つまり、Compare の要件を満たすオブジェクト) 。比較関数のシグネチャは、次と同等である必要があります。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;
}
lower_boundの呼び出しに渡されるラムダのパラメーターの順序valueは、 が最初のパラメーターとしてconst std::string&渡されるため、逆にする必要がありcompますが、このようにコンパイルされ、別の方法で渡されるとコンパイル エラーが発生します。
ここで何が欠けていますか?