Search code examples
c++stllower-bound

Using curly brackets instead of make_pair giving error


It gives no instance of overloaded function "lower_bound" matches the argument list error. I don't understand this behavior as curly brackets work fine in general while making a pair.

Using curly brackets:

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

Using make pair:

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

Solution

  • Compiler has no possiblility to deduce {2, 3} to std::pair<int, int> in this context. See the declaration of lower_bound:

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

    Compiler cannot assume that T should be equal to decltype(*first), because it doesn't have to be the case - it's only required that they are comparable.

    You need to disambiguate by actually naming the type you want to use - either by calling std::make_pair(2, 3) or by creating a temporary: std::pair{2, 3} (template arguments can be ommitted since C++17, for earlier standard you need std::pair<int, int>{2, 3} or make_pair).