Why `std` prefix is not required to call the `lower_bound` function?

187 Views Asked by At

Just for curiosity, I found a rather strange exception, that you can use a lower_bound function without telling in which namespace it is located. The following code:

// main.cpp
#include <algorithm>
#include <cstdio>
#include <vector>

// The std prefix is required for the vector, but not for the lower_bound, why?
using std::vector;

int main() {
    vector<int> v = {0,1,2,3,4,5};
    int index = lower_bound(v.begin(), v.end(), 2) - v.begin();
    // prints 2, as expected.
    printf("%d\n", index);
    return 0;
}

compiles with g++ main.cpp command, g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 compiler.

Question: does lower_bound belong to any namespace? If no, what's the motivation for such design?

1

There are 1 best solutions below

0
On BEST ANSWER

lower_bound() is indeed in the std namespace, as expected. The reason you can call it without specifying the std:: prefix is because of Argument-Dependent Lookup. You are passing std::vector iterators to lower_bound(), and those iterator types happen to reside in the std namespace in your compiler's implementation of std::vector. So, the compiler looks for the unqualified lower_bound() function in BOTH the global namespace AND the std namespace, finding the latter.