试图用C ++输出数组对象

时间:2013-04-09 21:04:35

标签: c++ class output

我正在编写一个程序来表示一个包含大量元素的数组,其中大部分为0且不超过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;
}

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:3)

同样更改此行以初始化数组,valueArray需要下标。

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

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