我现在是用计数排序的方法来排序,关于这个方法更详细的解释可以引用counting_sort 代码如下:
#include <iterator>
#include <limits>
template <typename iterator>
void counting_sort(iterator const &begin, iterator const &end)
{
typedef std::iterator_traits<iterator>::value_type T;
T max = std::numeric_limits<T>::max();
T freq[max+1] = {0};
iterator it;
T c;
for (it = begin; it < end; ++it) {
freq[*it] += 1;
}
for (c = 0, it = begin; c < max; ++c)
while (freq[c]-- > 0) {
*it++ = c;
}
}
while (freq[c]-- > 0) {
*it++ = c;
}
}
我很难使用代码进行排序。例如,
int main(void)
{
const int NUM=20;
unsigned char a[NUM];
for(int i=0; i<NUM; i++)
a[i] = i;
a[0] = 100;
a[3] = 15;
std::vector<unsigned char> aArray(a,a+NUM);
counting_sort(aArray.begin(),aArray.end());
for(int i=0; i<aArray.size(); i++)
{
int value = aArray[i];
std::cout<<value<<std::endl;
}
return 0;
}
我总是编译T freq[max+1] = {0}
错误,错误信息如下:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
关于如何使用代码有什么想法吗?谢谢。
最佳答案
在 C++(而不是 C)中,你不能声明一个可变长度的数组。如果 max
是一个常量,那么你的表达式就是正确的。决定是将 freq
声明为 std::vector
std::vector< T > freq( (size_t)max + 1, 0 );
另一件事:max
是最大数,可以用T
表示,这就是为什么max+1
是非法的。你可以试试这个:
T [ (size_t)std::numeric_limits<T>::max() + 1 ] = {0};
关于c++ - 如何在 C++ 中使用计数排序方法实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24323120/