gpt4 book ai didi

c++ - 使用不带前缀 "std"且不带 "using namespace std;"的 std::sort() 编译成功

转载 作者:可可西里 更新时间:2023-11-01 15:51:51 26 4
gpt4 key购买 nike

由于 sort() 是在 namespace std 中定义的,因此它必须始终用作 std::sort。但以下代码编译正确即使没有 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 与此有关。但我无法弄清楚。

最佳答案

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

对于 vector ,在通常的名称查找失败后,编译器会搜索 __gnu_cxxstd sort 的命名空间功能,__gnu_cxx因为它是 __gnu_cxx::normal_iterator 的命名空间和 std因为它是模板参数之一的命名空间,std::vector<int, std::allocator<int> > .它找到 std::sort .

对于 std::array , 迭代器就是 int* s,因此依赖于参数的查找不会搜索其他 namespace ,也不会找到 sort功能。

关于c++ - 使用不带前缀 "std"且不带 "using namespace std;"的 std::sort() 编译成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41491995/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com