2

我正在编写一个程序来表示一个包含大量元素的数组,其中大多数元素为零且不超过 20 个非零。理论上,该数组可以有一万亿个元素,但两个单独的数组将表示两个非零元素的数组索引和值。我现在遇到的问题是我无法输出值数组以进行调试。当我尝试输出值数组时,我得到的只是零,但是当我输出总数时,我得到 820。此外,这是一个家庭作业,我不能更改任何公共类声明,除了当我自己编写调试时的输出功能。谢谢您的帮助。

class SparseArray{
public:
    SparseArray();  //  construct an SparseArray with no nonzero elements
    unsigned get( unsigned long long index );   //  return an element from the      array
    SparseArray & set( unsigned long long index, unsigned value );  //  set array     element to value
    SparseArray & output ();
private:
    unsigned long long indexArray[21];
    unsigned valueArray[21];
    unsigned nonzero;


};  //  SparseArray


int main(int argc, const char * argv[])
{

    SparseArray a;
    unsigned long long index = 1;
    for(  unsigned i = 0;  i <= 20;  i++, index *= 4  )
        a.set( index, i );
        a.output();

    unsigned total = 0;
    index = 1;
    for(  unsigned i = 0;  i <= 40;  i++, index *= 2 ){
        total += a.get(index);
        a.output();
    }
    cout <<total;

    return 0;
}

SparseArray::SparseArray():
indexArray(),valueArray()
{
    for (int i = 0; i < 20; i++) {
        indexArray[i] = 0;
        valueArray[i] = 0;
    }

}
unsigned SparseArray::get( unsigned long long index ){

    unsigned object;

    for (unsigned i = 0; i < 20; i++) {
        if (indexArray[i] == index) {
            object = valueArray[i];
        }
    }

    return object;
}
SparseArray & SparseArray::set( unsigned long long index, unsigned value ){

   for (int i = 0; i < 20; i++) {
        if (indexArray[i] == 0 && valueArray == 0) {
            indexArray[i] = index;
            valueArray[i] = value;
           break;
         }
    }

    return *this;


    }

SparseArray & SparseArray::output (){
    for (int k = 0; k < 21; k++) {
        cout << valueArray[k] << "," << endl;
    }

    return *this;
}
4

2 回答 2

3

此循环迭代21次。

for (int k = 0; k < 21; k++)

这就是您的输出返回 820 的原因。

unsigned object; // This can be returned uninitialized data!  Set it to 0!

for (unsigned i = 0; i < 20; i++) {
    if (indexArray[i] == index) {
        object = valueArray[i];
    }
}

return object;
于 2013-04-09T21:13:42.770 回答
3

还要更改此行以初始化数组, valueArray 需要一个下标。

if (indexArray[i] == 0 && valueArray == 0) {

if (indexArray[i] == 0 && valueArray[i] == 0) {
于 2013-04-09T21:15:50.043 回答