2014-02-11 83 views
0

它表示實現if語句時矢量下標超出範圍。我想我增加了額外的int到floor,或者額外的floor vector到2D vector。我正在使用VS 2010(C++) 我試圖在其他問題上找到它,但沒有成功。2D矢量下標超出範圍

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; 
     } 
+0

你需要is_perfect_square函數中的「floor」嗎? – shaoyl85

+1

另外,'for(int i = 0; i <= hotel.size(); i ++)'是無效的,因爲您正在訪問下面的[hotel] [hotel]。下標的範圍從0到hotel.size() - 1 – shaoyl85

回答

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; 
    }