c++ - 如何在 C++ 中使用计数排序方法实现

标签 c++ visual-studio-2010

我现在是用计数排序的方法来排序,关于这个方法更详细的解释可以引用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/

相关文章:

c++ - 组合多个变量以作为 udp 数据包发送

c++ - 为什么不消除关于此结构的填充字节的需要?

visual-studio-2010 - 我是否需要 Team Foundation 服务器才能使用 CodedUI?

c++ - C++ 中的公共(public)字段或类似 C# 的属性?

c++ - 在 C++ 中删除动态字符**

c++ - 使用常量引用进行赋值

visual-studio-2010 - 有没有人设法让 katmouse 超过 2010 年

xml - 除 web.config 之外的配置文件的 xdt 转换

c++ - Visual Studio 2010 Qt 插件 Cmake 项目

c++ - 一旦 std :thread makes into C++Ox,pthreads 会过时吗