数组下标错误的类型int [int]无效

时间:2015-04-11 03:00:36

标签: c++

我一直收到上面列出的错误方法。以下是相关代码:

BubbleSort<int> bs;
analysis << "Working with Bubble Sort with " << size << " random elements\n";
start = clock();
for(int i=0;i<=size;i++)
{
   bs.sort(array[size], 1+(rand() )); --> error
}


这是我的头文件:

#ifndef BUBBLESORT_H_
#define BUBBLESORT_H_
#include <iostream>

using namespace std;

template <class Type>
class BubbleSort
{
    private:

    public:
    int array[], size;
    Type sort(Type array[], Type size);
};

    template<class Type> 
    Type
    BubbleSort<Type>::sort(Type array[], Type size)
    {
        int i, j, flag = 1;
        int num_cmps = 0;
        int temp;
        for (i = 1; (i <= size) && flag; i++)
        {
        flag = 0;
            for (j = 0; j < (size - 1); j++)
            {
                if(array[j+1] < array[j])
                {
                temp = array[j];
                ++num_cmps;
                array[j] = array[j+1];
                ++num_cmps;
                array[j+1] = temp;
                ++num_cmps;
                flag = 1;
                ++num_cmps;
                }
            }
        }
    }
    #endif

之前我曾向用户询问过元素数量,然后是cin >> size;。我认为这会使size不变,这是我的研究告诉我的是这个错误的问题。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

问题1

BubbleSort中,而不是

Type sort(Type array[], Type size);

您需要以下内容:

Type sort(Type array[], size_t size); 

问题2

当您调用该函数时,

array[size]评估为int,而不是数组。使用:

bs.sort(array, size);

答案 1 :(得分:0)

bs.sort(array[size], 1+(rand() ));

函数sort需要一个数组,但是你要在array中传递索引size的项目(可能超出范围)