Using std::sort() without prefix “std” and also without “using namespace std;” compiles successfully

后端 未结 2 1940
再見小時候
再見小時候 2020-12-16 01:24

As sort() is defined in namespace std it must always be used as std::sort.But the following code compiles correctly even without

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 01:44

    This is argument dependent lookup. According to Stroustroup's The C++ Programming Language: 4th Edition, there are two rules that apply here:

    1) If an argument is a member of a namespace, the associated namespaces are the enclosing namespaces.

    2) If an argument is a built-in type, there are no associated namespaces.

    In your first and second cases, begin() and end() return iterators. However, the C++ standard defines an iterator as any variable of any type, upon which an iteration operation can be performed. (In other words, an iterator is a design concept that is enforced via a template.)

    According to the other answer, the iterators in the first case are variables of a data type that belongs to the same namespace as sort(). However, the iterators in the second case have a primitive data type. Per Rule #2, these iterators have no associated namespace.

提交回复
热议问题