C++ 11 std :: begin不能与传递给模板函数的int []一起使用

kre*_*ems 3 c++ templates c++11

我有一个问题:没有匹配函数来调用'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;
}
Run Code Online (Sandbox Code Playgroud)

有什么问题?我该如何解决?

jro*_*rok 9

void heapSort(T array[]);
Run Code Online (Sandbox Code Playgroud)

只是替代语法

void heapSort(T* array);
Run Code Online (Sandbox Code Playgroud)

您不能按值传递数组,因此您需要通过引用获取它(并且可能让编译器推断它的大小):

template<typename T, size_t N>
void heapSort(T (&array)[N]);
Run Code Online (Sandbox Code Playgroud)

请注意,通过这种方式,您将为每个不同大小的数组获得不同的实例化.如果你有大量的数组,它可能会导致一些代码膨胀.我考虑使用一个std::vector代替.

  • 而不是`vector`或数组,最好的方法是采用第一个和最后一个迭代器...`template <class RandomIt> void heapSort(RandomIt first,RandomIt last)`(注意模板参数是以[为[标准迭代器模板策略](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator)它是必需的) (3认同)