我遇到了一个问题:没有匹配函数来调用“begin(int*&)” 我发现的唯一提示是编译器在编译时可能不知道数组的大小,但我相信这不是我的情况。 这是我得到的:
template <typename T>
void heapSort(T array[]) {
size_t length = std::end(array) - std::begin(array);
if (length == 0) {
return;
}
Heap<T> heap(array);
for (size_t i = length - 1; i >= 0; --i) {
array[i] = heap.pop();
}
}
int main() {
int array[] = {9, 8, 10, 99, 100, 0};
for (auto i = 0; i < 6; ++i) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
heapSort(array);
for (auto i = 0; i < 6; ++i) {
std::cout << array[i] << " ";
}
std::cout << std::endl;
}
有什么问题?我该如何解决?
最佳答案
void heapSort(T array[]);
只是
的替代语法void heapSort(T* array);
你不能按值传递数组,所以你需要通过引用来获取它(并且可能让编译器推断它的大小):
template<typename T, size_t N>
void heapSort(T (&array)[N]);
请注意,通过这种方式,您将为每个不同大小的数组获得不同的实例化。如果你有大量的数组,它可能会导致一些代码膨胀。我会考虑改用 std::vector
。
关于C++11 std::begin 不适用于传入模板函数的 int[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223564/