使用动态数组对算法编译器错误进行排序
sort algorithm compiler error with dynamic array
我很难让 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
。您将其分配给指向 10000000int
秒。但是一旦你分配了它,你最终得到的只是一个指向int
的指针,仅此而已。由您的代码来跟踪此指针指向您的确切内容。如果你要写,你最终会用同样的指针结束,简单地说:
int n;
int *numbers=&n;
此numbers
指针与您创建的指针完全相同。它只是一个指向int
的指针。仅此而已,仅此而已。
std::begin()
和std::end()
不适用于普通指针,例如指向此处int
的指针,因为,正如我刚才所说,指向某个对象的指针没有任何内容可以指示它指向多少个连续的对象。它可能是一个int
.可能是两个int
秒。也许一百万。或者也许什么都没有,如果指针是nullptr
.
如果要对动态分配的int
数组进行排序,只需直接传递开始指针和结束指针:
std::sort(number, numbers+10000000);
相关文章:
- C++选择排序算法中的逻辑错误
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 对单向链表进行排序时出现运行时错误
- 无法在我的堆排序代码中找到错误.无法正确执行.C++
- 在气泡排序程序中未声明错误功能
- 仅在大型阵列上出现合并排序分段错误
- 分段 排序函数实现中的错误
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 字符串上的合并排序上的 Seg 错误
- 将图形表示为unordered_map<字符串、向量>时拓扑排序错误<string>
- C++为什么我的指针选择排序中存在分段错误?
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 尝试按值对地图进行排序,但出现错误
- 使用快速排序对 C++ 中的可视化工具错误进行排序
- 合并排序:分段错误核心转储
- 比较迭代器会使程序崩溃,而不会在自定义气泡排序实现中出现错误
- 合并排序中的错误计数:计数反转
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- C++中的错误排序算法