为什么调用 `lower_bound` 函数不需要 `std` 前缀?

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

出于好奇,我发现了一个相当奇怪的异常,您可以使用 lower_bound 函数而无需告知它位于哪个名称空间中。以下代码:

// 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;
}

使用 g++ main.cpp 命令编译,g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 编译器。

问题lower_bound是否属于任何命名空间?如果不是,这样设计的动机是什么?

正如预期的那样,

lower_bound() 确实在 std 命名空间中。您可以在不指定 std:: 前缀的情况下调用它的原因是 Argument-Dependent Lookup。您正在将 std::vector 迭代器传递给 lower_bound(),而这些迭代器类型恰好驻留在编译器的 std::vector 实现中的 std 名称空间中。因此,编译器在 BOTH 全局命名空间 AND std 命名空间中查找不合格的 lower_bound() 函数,找到后者。