Sukhanov Niсkolay Sukhanov Niсkolay - 9 months ago 45
C++ Question

Why is a sort function in the global namespace?

Why is there a sort function in the global namespace in C++? Why this code compiles?

#include <iostream>
#include <vector>

int main() {
std::vector<int> array(10);
sort(array.begin(), array.end());

PS: clang++ --std=c++11 --stdlib=libc++ ./test.cpp


sort isn't in the global namespace, it's in std. However, the result type of vector::begin() may be in std too (this is implementation-dependent). If so then std::sort is found by ADL (argument-dependent lookup).

If you don't want std::sort to be found by ADL then you can make a qualified call to sort instead of an unqualified one: ::sort(array.begin(), array.end()).