visual studio 2010 - How to use counting sort method implementation in C++ -
visual studio 2010 - How to use counting sort method implementation in C++ -
i using counting sort method sorting, , more detailed explanation method, please refer counting_sort codes 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; (it = begin; < end; ++it) { freq[*it] += 1; } (c = 0, = begin; c < max; ++c) while (freq[c]-- > 0) { *it++ = c; } } while (freq[c]-- > 0) { *it++ = c; } }
i have hard in using codes perform sorting. 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; } homecoming 0; }
i have compilation errors t freq[max+1] = {0}
, error messages follows:
error c2057: expected constant look error c2466: cannot allocate array of constant size 0
any ideas on how utilize codes? thanks.
in c++ (instead od c) can't declare array variable length. if max
constant, look right. decision declare freq
std::vector
std::vector< t > freq( (size_t)max + 1, 0 );
another thing: max
maximum number, can represented in t
, that's why max+1
illegal. can seek this:
t [ (size_t)std::numeric_limits<t>::max() + 1 ] = {0};
c++ visual-studio-2010
Comments
Post a Comment