我在与C++作斗争。我以前学过Java,我觉得它容易多了,TBH。目前,我正在尝试用C++编写一个计数排序算法。我想获得数组的最大值,以声明我的帮助数组,其大小为=最大值+1;我试了好几种方法,但都不管用。它总是显示“变量不能用作常量”。我也找到了一个代码,它做同样的我,但似乎是工作。有人能给我一些提示或解决办法吗?
提前谢谢你。
#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
int getMax(int arr[], int size)
{
int max = arr[0];
for (int i = 1; i < sizeof(arr); i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
void countingSort(int *arr, int size)
{
int max = getMax(arr, size);
int hilfsArr[max + 1];
}
不能将变量用于编译时数组大小,因为编译器无法知道getmax
函数返回的值是什么。。。
在这种情况下需要使用动态数组。。。
void countingSort(int *arr, int size)
{
int max = getMax(arr, size);
int *hilfsArr=new int[max + 1]; // allocate
... here put the rest of your code for this function
delete[] hilfsArr; // free before exiting function
}
对于动态大小的数组,只需使用std::vector
,类似于:
void countingSort(int *arr, int size)
{
std::vector<int> counter(*std::max_element(arr, arr + size));
// ...
}