使用大括号而不是 make_pair 给出错误

Using curly brackets instead of make_pair giving error

它给出 no instance of overloaded function "lower_bound" matches the argument list 错误。我不明白这种行为,因为大括号在配对时通常可以正常工作。

使用大括号:

vector<pair<int, int>> a;
auto ptr = lower_bound(a.begin(), a.end(), {2, 3});

使用配对:

vector<pair<int, int>> a;
auto ptr = lower_bound(a.begin(), a.end(), make_pair(2, 3));

在此上下文中,编译器无法将 {2, 3} 推断为 std::pair<int, int>。见lower_bound的声明:

template< class ForwardIt, class T >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );

编译器不能假定 T 应该等于 decltype(*first),因为情况不一定如此 - 只要求它们具有可比性。

您需要通过实际命名您要使用的类型来消除歧义 - 通过调用 std::make_pair(2, 3) 或创建一个临时的:std::pair{2, 3}(自 C++17 起可以省略模板参数,对于较早的标准,您需要 std::pair<int, int>{2, 3}make_pair).

解释了为什么您的第一个代码片段无法编译(即为什么编译器无法正确推断出 lower_bound 的第三个参数的类型);它还提供了两种解决问题的方法,两种方法都非常明智。

不过,还有第三种的可能性——虽然是不是'sensible'是主观判断。因此,为了完整起见,我将在这里说明该方法......

您可以显式在您的调用中为lower_bound提供模板参数,这使编译器能够正确解释第三个参数的类型:

#include <vector>
#include <algorithm>
#include <type_traits>
using namespace std;
int main(void)
{
    vector<pair<int, int>> a;
    auto ptr = lower_bound< decltype(a.begin()),pair<int,int> >(a.begin(),a.end(),{2,3});
    //...
    return 0;
}

以下是 lower_bound 的规范(取自 cppreference):

template< class ForwardIt, class T >
ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );

因此,在我提供的代码中,我们明确指定了 ForwardIt class T 的类型(如 pair<int,int> ), 因此第三个函数参数将是 known 是对这种类型的 const 引用,并且该类型的 deduction 将不需要。