Reputation: 11753
I am now using a counting sort method to do the sorting, and for more detailed explanation about this method, please refer to counting_sort The codes are as follows:
#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;
}
}
I have difficult in using the codes to perform sorting. For example,
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;
}
I always have compilation errors for T freq[max+1] = {0}
, the error messages are as follows:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
Any ideas on how to use the codes? Thanks.
Upvotes: 0
Views: 124
Reputation: 5054
In C++ (instead od C) you can't declare an array with variable length. If max
would be a constant, then you expression will be right. The decision is to declare a freq
as a std::vector
std::vector< T > freq( (size_t)max + 1, 0 );
Another thing: max
is a maximum number, that can be represented in T
, that's why max+1
is illegal. You can try this:
T [ (size_t)std::numeric_limits<T>::max() + 1 ] = {0};
Upvotes: 3