2D矢量下标超出范围

时间:2014-02-11 02:32:07

标签: 2d-vector

当实现if语句时,它表示向量下标超出范围。我想我在地板上添加了额外的int,或者向2D矢量添加了额外的地板矢量。我正在使用VS 2010(C ++) 我试图在其他问题上找到它但没有成功。

bool is_perfect_square(int);
    int main()
    {
        int cust;
        vector<int>floor;
        vector<vector<int>>hotel;
        floor.push_back(0);
        hotel.push_back(floor);
        hotel[0][0]=1;
        for(cust=2; ; cust++)
        {
            for(int i=0; i<=hotel.size(); i++)
            {
                if(is_perfect_square(cust+hotel[i][floor.size()]))
                {
                    floor.push_back(0);
                    hotel[i][cust]=cust;
                    break;
                }
                else
                {
                    hotel.push_back(floor);
                    hotel[hotel.size()][0]=cust;
                }
            }
        }

        int sum=0;
            for(int a=1; a<=hotel.size(); a++)
            {
                for(int b=1; b<=floor.size(); b++)
                {
                    if(pow(a-1,2)+pow(b-1,2)==14234886498625)
                        sum+=hotel[a-1][b-1];
                }
            }



            cout<<sum<<endl;    
        system("pause");
        return 0;
    }

    bool is_perfect_square(int n)
        {
            int root=floor(sqrt(n));
            return n == root * root;
        }

1 个答案:

答案 0 :(得分:0)

我在评论中提出了答案。

bool is_perfect_square(int);
int main()
{
    int cust;
    vector<int>floor;
    vector<vector<int>>hotel;
    floor.push_back(0);
    hotel.push_back(floor);
    hotel[0][0]=1;

    // you may not be able to get out of this loop 
    // because the "break" below only exits one level of the loop.
    for(cust=2; ; cust++)
    {
        // this should be changed to "i<hotel.size()", 
        // because the subscript of a vector ranges from 0 to its size minus one.
        for(int i=0; i<=hotel.size(); i++)
        {
            // here "floor.size()" should be floor.size() - 1, the same reason.
            if(is_perfect_square(cust+hotel[i][floor.size()]))
            {
                floor.push_back(0);
                hotel[i][cust]=cust;
                break;
            }
            else
            {
                hotel.push_back(floor);
                hotel[hotel.size()][0]=cust;
            }
        }
    }

    int sum=0;
        for(int a=1; a<=hotel.size(); a++)
        {
            for(int b=1; b<=floor.size(); b++)
            {
                if(pow(a-1,2)+pow(b-1,2)==14234886498625)
                    sum+=hotel[a-1][b-1];
            }
        }



        cout<<sum<<endl;    
    system("pause");
    return 0;
}

bool is_perfect_square(int n)
    {
        int root=floor(sqrt(n));
        return n == root * root;
    }