简体   繁体   English

错误 output C++ ArrayList

[英]Wrong output C++ ArrayList

When i make ArrayList with size 5 it gives wrong result but when it becomes bigger than 5 it becomes correct!当我制作尺寸为 5 的 ArrayList 时,它给出了错误的结果,但是当它变得大于 5 时,它变得正确!

#include <iostream>
#include <string>

using namespace std;

class list
{
    typedef int ListElemtype;
private:
    ListElemtype listArray[6];
public:
    bool insert(ListElemtype e)
    {
        if (numberOfElements == 5) //It turns wrong result when ListArray equal 5??
        {
            cout << "Can't do the insertion" << endl;
            return false;
        } //Why it return false? I know why i but = instead of == :D
        else
        {
            listArray[numberOfElements + 1] = e;
            numberOfElements++;
            cout << "Done perfectly!" << numberOfElements << endl;
            return true;
        }
    };

    bool first(ListElemtype &e);
    bool next(ListElemtype &e);
    int numberOfElements;
    int CurrentPosition;

    void LIST ()
    {
        CurrentPosition=-1;
        numberOfElements=0;
        return;
    }
};

int main()
{
    list A;
    A.LIST();
    A.insert(10);
    A.insert(20);
    A.insert(30);
    A.insert(40);
    A.insert(50);
    A.insert(60);
    system("pause");
    return 0;
}

Arrays are indexed from zero, not from one. Arrays 从零开始索引,而不是从一开始。 So listArray[numberOfElements+1]=e;所以listArray[numberOfElements+1]=e; should be listArray[numberOfElements]=e;应该是listArray[numberOfElements]=e; . . The first inserted element goes into listArray[0] .第一个插入的元素进入listArray[0]

Your listArray size is 6 therefore array index would start from 0 till 5. When you have numberOfElements==5 with listArray[numberOfElements + 1] you are trying to store at index 6 which you don't have.您的listArray大小为 6,因此数组索引将从 0 到 5 开始。当您有numberOfElements==5listArray[numberOfElements + 1]时,您试图存储在您没有的索引 6 处。

As you may know, C bases its arrays at 0 and not 1 .如您所知, C 将其 arrays 设置为0而不是1 Thus,因此,

 else { listArray[numberOfElements+1]=e;

writes to the end of the array contained within list A , when numberOfElements is equal to 5 or higher.numberOfElements等于 5 或更高时,写入包含在list A中的数组的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM