c – 使用没有前缀“std”的std :: sort(),也不使用“using name
发布时间:2020-12-16 05:47:32 所属栏目:百科 来源:网络整理
导读:由于sort()在命名空间std中定义,因此必须始终将其用作std :: sort.But即使没有std也可以正确编译. #include vector#include algorithmint main(){ std::vectorint nums = {4,3,1,7,2,0}; sort(nums.begin(),nums.end());} ideone.com 但是这个代码没有. #inc
由于sort()在命名空间std中定义,因此必须始终将其用作std :: sort.But即使没有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,8,9,6}; sort(nums.begin(),nums.end()); } 使用gcc 4.8.4与-std = c 11标志启用. 从这两个代码片段可以清楚的看出,std :: vector与此有关.但我无法理解. 解决方法
这是
argument-dependent lookup.如果使用typeid来检查涉及的迭代器的类型:
#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; } 至少在Ideone,你得到以下输出: N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE Pi 使用Revolver_Ocelot在注释中的帮助,我们看到这些类型是__gnu_cxx :: __ normal_iterator< int *,std :: vector< int,std :: allocator< int> > >和int *. 对于向量,在通常的名称查找失败之后,编译器会在__gnu_cxx和std命名空间中搜索排序函数__gnu_cxx,因为它是__gnu_cxx :: normal_iterator和std的命名空间,因为它是一个模板参数的命名空间std ::向量< int,std :: allocator< int>取代.它发现std :: sort. 对于std ::数组,迭代器只是int *,因此参数相关的查找不会搜索其他命名空间,并且没有找到排序函数. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |