Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

c++ - Using std::sort() without prefix "std" and also without "using namespace std;" compiles successfully

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());
}

ideone.com

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is argument-dependent lookup. If you use typeid to examine the types of the iterators involved:

#include <iostream>
#include <typeinfo>
#include <vector>
#include <array>

int main() {
    std::cout << typeid(std::vector<int>::iterator).name() << '
';
    std::cout << typeid(std::array<int, 5>::iterator).name() << std::endl;
    return 0;
}

at least on Ideone, you get the following output:

N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE
Pi

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> > > and int*.

For the vector, after the usual name lookup fails, the compiler searches the __gnu_cxx and std namespaces for a sort function, __gnu_cxx because it's the namespace of __gnu_cxx::normal_iterator and std because it's the namespace of one of the template arguments, std::vector<int, std::allocator<int> >. It finds std::sort.

For the std::array, the iterators are just int*s, so argument-dependent lookup searches no additional namespaces and finds no sort function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...