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?
lower_bound()
is indeed in thestd
namespace, as expected. The reason you can call it without specifying thestd::
prefix is because of Argument-Dependent Lookup. You are passingstd::vector
iterators tolower_bound()
, and those iterator types happen to reside in thestd
namespace in your compiler's implementation ofstd::vector
. So, the compiler looks for the unqualifiedlower_bound()
function in BOTH the global namespace AND thestd
namespace, finding the latter.