[英]Passing pointer to an array into a function (C++)
I'm trying to pass an array into my function calls for build_max_heap and max_heapify so I can modify the array after each call, but I receive an error saying "candidate function not viable: no known conversion from 'int [9]' to 'int *&'for 1st argument." 我正在尝试将数组传递给我的函数调用build_max_heap和max_heapify,所以我可以在每次调用后修改数组,但是我收到一条错误,说“候选函数不可行:没有已知的从'int [9]'转换为' int *&'为第一个参数。“
#include <iostream>
#include <string>
using namespace std;
void build_max_heap(int*& array, int size);
void max_heapify(int*& array, int size, int index);
void build_max_heap(int*& array, int size)
{
for(int i = size/2; i>=0; i--)
{
max_heapify(array, i);
}
}
void max_heapify(int*& array, int size, int index)
{
int leftChild = 2*index+1;
int rightChild = 2*index+2;
int largest;
int heap_size = size;
if( leftChild <= heap_size && array[leftChild] > array[index])
largest = leftChild;
else
largest = index;
if(rightChild <= heap_size && array[rightChild] > array[largest])
largest = rightChild;
if(largest != index) {
int tempArray = array[index];
array[index] = array[largest];
array[largest] = tempArray;
max_heapify(array, heap_size, largest);
}
}
int main()
{
int array[]={5,3,17,10,84,19,6,22,9};
int size = sizeof(array)/sizeof(array[0]);
build_max_heap(array, size);
return 0;
}
int array[]={5,3,17,10,84,19,6,22,9};
While array
can be decayed to a pointer int*
to be passed as a function argument, it the pointer cannot be passed as a "non-const reference" int*&
, because it is immutable (it is a constant address). 虽然
array
可以衰减为指针int*
以作为函数参数传递,但指针不能作为“非const引用” int*&
传递,因为它是不可变的(它是一个常量地址)。 You could have passed it as a const reference like this: 您可以将它作为const引用传递,如下所示:
void max_heapify(int* const& array, int size, int index)
// ^^^^^^
However, this doesn't make much sense, you can simply pass the pointer by value (a copy of the address of the array), which results in the same: the variable at the caller wont be changed. 但是,这没有多大意义,您可以简单地按值传递指针(数组地址的副本),这会导致相同的结果:调用者的变量不会被更改。 The usual use case of
const&
parameters is to pass objects that are expensive to copy, such as std::string
. const&
参数的通常用例是传递复制成本高的对象,例如std::string
。 This does not apply to pointers; 这不适用于指针; making a copy of a pointer is as cheap as copying any basic variable.
制作指针的副本与复制任何基本变量一样便宜。
You should change your functions to take the pointer by value: 您应该更改函数以按值获取指针:
void build_max_heap(int* array, int size)
void max_heapify(int* array, int size, int index)
also, correct the call to max_heapify
inside build_max_heap
, give it the correct number of arguments: 同时,纠正调用
max_heapify
内build_max_heap
,给它正确的参数个数:
void build_max_heap(int* array, int size)
{
for(int i = size/2; i>=0; i--)
{
max_heapify(array, size, i); // <-- 3 arguments
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.