c++ - 动态数组的排序算法编译器错误

标签 c++ c arrays

我很难让 std::begin() 处理动态分配的数组(指针),而它似乎可以很好地处理堆栈分配的数组。

这个有效:

int numbers[100];

// Fill array with numbers

std::sort(std::begin(numbers), std::end(numbers));

这不是

int* numbers = new int[10000000];

// Fill array with numbers

std::sort(std::begin(numbers), std::end(numbers));

这是产生的错误。

ptests.cpp:120:33: error: no matching function for call to ‘begin(int*&)’
     std::sort(std::begin(numbers), std::end(numbers));
                                 ^
ptests.cpp:120:33: note: candidates are:
In file included from /usr/include/c++/4.8/utility:74:0,
                 from /usr/include/c++/4.8/algorithm:60,
                 from ptests.cpp:1:
/usr/include/c++/4.8/initializer_list:89:5: note: template<class _Tp> constexpr const _Tp* std::begin(std::initializer_list<_Tp>)
     begin(initializer_list<_Tp> __ils) noexcept
     ^
/usr/include/c++/4.8/initializer_list:89:5: note:   template argument deduction/substitution failed:
ptests.cpp:120:33: note:   mismatched types ‘std::initializer_list<_Tp>’ and ‘int*’
     std::sort(std::begin(numbers), std::end(numbers));
                                 ^
In file included from /usr/include/c++/4.8/string:51:0,
                 from /usr/include/c++/4.8/random:41,
                 from /usr/include/c++/4.8/bits/stl_algo.h:65,
                 from /usr/include/c++/4.8/algorithm:62,
                 from ptests.cpp:1:
/usr/include/c++/4.8/bits/range_access.h:48:5: note: template<class _Container> decltype (__cont.begin()) std::begin(_Container&)
     begin(_Container& __cont) -> decltype(__cont.begin())

是否可以将动态指针转换为 begin() 期望的类型?任何建议将不胜感激!

最佳答案

std::end(numbers)

这个numbers变量是一个

int *

这就是它的类型。这个指向整数的指针并没有告诉任何人它指向多少个int。您将其分配为指向 10000000 个 int。但是一旦你分配了它,你最终得到的只是一个指向 int 的指针,仅此而已。由您的代码来跟踪这个指针究竟指向您什么。如果你要写,你会得到完全相同的指针,简单地说:

int n;

int *numbers=&n;

numbers 指针与您创建的指针完全相同。它只是一个指向 int 的指针。仅此而已。

std::begin()std::end() 不适用于普通指针,比如指向 int 的指针在这里,因为,正如我刚才所说,指向某个对象的指针并没有指示它指向多少个连续对象。它可以是一个 int。它可以是两个 int。也许一百万。如果指针是一个 nullptr,也可能什么都不是。

如果您想对动态分配的 int 数组进行排序,只需直接传递开始和结束指针即可:

std::sort(number, numbers+10000000);

关于c++ - 动态数组的排序算法编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45123882/

相关文章:

c - 在函数中设置指向结构体的指针的成员

c - 将一个字节递增一个,就好像它是一个 Base10 数字一样

c++ - 为什么 union 的规模比预期的要大?

c++ - 在我的C++ CaesarCipher程序中出现错误

c - 如何使守护进程的子进程在 Linux 中交互?

javascript - 嵌套数组操作奇怪的行为,js

arrays - 如何精确地将 "grep"与点 "."对齐?

php - 获取 HTML 标签之间的文本

c++ - 在类中初始化静态 union

c++ - 修复 std::map 中的碰撞内存泄漏