C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 使用没有前缀“std”的std :: sort(),也不使用“using namespace std”编译成功大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
由于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 *,因此参数相关的查找不会搜索其他命名空间,并且没有找到排序函数.

大佬总结

以上是大佬教程为你收集整理的c – 使用没有前缀“std”的std :: sort(),也不使用“using namespace std”编译成功全部内容,希望文章能够帮你解决c – 使用没有前缀“std”的std :: sort(),也不使用“using namespace std”编译成功所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。