【问题标题】:Passing pointer to an array into a function (C++)将指向数组的指针传递给函数(C++)
【发布时间】:2017-08-09 17:31:54
【问题描述】:

我正在尝试将一个数组传递给我的函数调用 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;
}

【问题讨论】:

  • max_heapify(array, i); 你的函数调用在build_max_heap 中是错误的。它需要 3 个参数。
  • 引用传递数组的方式不对,检查this
  • 你可以只传递一个指向函数的指针,而不是通过引用传递。

标签: c++ arrays pointers heap


【解决方案1】:

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

虽然 array 可以衰减为指针 int* 以作为函数参数传递,但指针不能作为“非常量引用”int*&amp; 传递,因为它是不可变的(它是常量地址)。您可以像这样将它作为 const 引用传递:

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

但是,这没有多大意义,您可以简单地按值传递指针(数组地址的副本),结果相同:调用者处的变量不会改变。 const&amp; 参数的常见用例是传递复制成本高的对象,例如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
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    相关资源
    最近更新 更多