Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 std::begin doesn't work with int[] passed into template function

I've got an issue: no matching function for call to ‘begin(int*&)’ The only hint I've found on it is that compiler might not know the size of array at compile time, but I believe that's not my case. Here is what I've got:

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;
}

What's the problem? How can I solve it?

like image 519
krems Avatar asked Jun 17 '26 09:06

krems


2 Answers

void heapSort(T array[]);

is just alternative syntax for

void heapSort(T* array);

You can't pass an array by value, so you need to take it by reference (and possibly let the compiler deduce its size):

template<typename T, size_t N>
void heapSort(T (&array)[N]);

Note that this way you'll get a different instantiation for each array of distinct size. It might lead to some code bloat if you've got a large number of arrays. I'd consider using a std::vector instead.

like image 54
jrok Avatar answered Jun 19 '26 01:06

jrok


Like jrok said, T array[] is just a synonym for a pointer T* array which looses any information about the actual array type.

If you really want to use a compile time array, it's actually

template<typename T,std::size_t N> void heapSort(T (&array)[N])

(And that's in the end what std::begin and std::end do, too.)

like image 26
Christian Rau Avatar answered Jun 18 '26 23:06

Christian Rau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!