As sort() is defined in namespace std it must always be used as std::sort.But the following code compiles correctly even without std.
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> nums = {4,3,1,7,2,0};
sort(nums.begin(),nums.end());
}
But this code doesn't.
#include <array>
#include <algorithm>
int main()
{
std::array<int,5> nums = {4,1,8,9,6};
sort(nums.begin(),nums.end());
}
Using gcc 4.8.4 with -std=c++11 flag enabled.
From both these code snippets it is clear that std::vector has something to do with this.But I can't figure it out.
This is argument-dependent lookup. If you use
typeidto examine the types of the iterators involved:at least on Ideone, you get the following output:
With Revolver_Ocelot's help in the comments, we see that these types are
__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >andint*.For the vector, after the usual name lookup fails, the compiler searches the
__gnu_cxxandstdnamespaces for asortfunction,__gnu_cxxbecause it's the namespace of__gnu_cxx::normal_iteratorandstdbecause it's the namespace of one of the template arguments,std::vector<int, std::allocator<int> >. It findsstd::sort.For the
std::array, the iterators are justint*s, so argument-dependent lookup searches no additional namespaces and finds nosortfunction.