将指向数组的指针传递给函数(C ++)

4
我试图将数组传递到我的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;
}

build_max_heap 中,你的函数调用 max_heapify(array, i) 是错误的。它需要三个参数。 - Ayush
1
你传递数组的引用方式是错误的,请查看这里 - Jiahao Cai
1
你可以直接传递一个指向函数的指针,而不是通过引用传递。 - Jiahao Cai
1个回答

4

int array[]={5,3,17,10,84,19,6,22,9};

尽管可以将 array 退化为指向整型的指针 int* 并作为函数参数传递,但指针不能被作为“非 const 引用” int*& 传递,因为它是不可变的(是一个常量地址)。您可以通过以下方式将其作为 const 引用传递:

void max_heapify(int* const& array, int size, int index)
//                    ^^^^^^

然而,这并没有太多意义,您可以通过传递指针的值(数组地址的副本)来实现同样的效果:调用者处的变量不会改变。 const&参数的通常用法是传递昂贵的复制对象,例如std::string。但这不适用于指针;复制指针与复制任何基本变量一样便宜。
您应该更改函数以按值接受指针:
void build_max_heap(int* array, int size)
void max_heapify(int* array, int size, int index)

此外,在 build_max_heap 中正确调用 max_heapify,并给出正确的参数数量:

void build_max_heap(int* array, int size)
{
   for(int i = size/2; i>=0; i--)
   {
       max_heapify(array, size, i);  // <-- 3 arguments
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接