我现在使用计数排序方法进行排序,有关此方法的更详细说明,请参阅排序代码如下:
#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对如何使用密码有什么想法吗?谢谢。
发布于 2014-06-20 08:52:08
在C++ (而不是od )中,不能声明可变长度的数组。如果max是一个常量,那么表达式将是正确的。这个决定是将一个freq声明为std::freq
std::vector< T > freq( (size_t)max + 1, 0 );另一件事:max是一个最大的数字,可以用T表示,这就是为什么max+1是非法的。你可以试试这个:
T [ (size_t)std::numeric_limits<T>::max() + 1 ] = {0};https://stackoverflow.com/questions/24323120
复制相似问题