使用不带前缀"std"的std :: sort()并且还没有“使用命名空间std;"编译成功 [英] Using std::sort() without prefix "std" and also without "using namespace std;" compiles successfully

查看:80
本文介绍了使用不带前缀"std"的std :: sort()并且还没有“使用命名空间std;"编译成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 sort()是在 namespace std 中定义的,因此必须始终将其用作 std :: sort .但是以下代码可以正确编译即使没有 std .

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

但是此代码没有.

#include <array>
#include <algorithm>

int main()
{

    std::array<int,5> nums = {4,1,8,9,6};
    sort(nums.begin(),nums.end());
}

使用启用了 -std = c ++ 11 标志的 gcc 4.8.4 .

从这两个代码片段中可以清楚地看到 std :: vector 与此有关,但我不知道.

From both these code snippets it is clear that std::vector has something to do with this.But I can't figure it out.

推荐答案

这是参数依赖的查询.如果使用 typeid 检查涉及的迭代器的类型:

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() << '\n';
    std::cout << typeid(std::array<int, 5>::iterator).name() << std::endl;
    return 0;
}

至少在 Idone 上,您将获得以下输出:

at least on Ideone, you get the following output:

N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE
Pi

在注释中的Revolver_Ocelot的帮助下,我们看到这些类型是 __ gnu_cxx :: __ normal_iterator< int *,std :: vector< int,std :: allocator< int>>> int * .

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

对于向量,在常规名称查找失败后,编译器在 __ gnu_cxx std 命名空间中搜索 sort 函数 __ gnu_cxx ,因为它是 __ gnu_cxx :: normal_iterator std 的命名空间,因为它是模板参数之一 std :: vector<的命名空间.int,std :: allocator< int>> .它会找到 std :: sort .

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.

对于 std :: array ,迭代器只是 int * ,因此依赖于参数的查找不会搜索其他名称空间,也不会找到 sort 函数.

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

这篇关于使用不带前缀"std"的std :: sort()并且还没有“使用命名空间std;"编译成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆