二维向量下标超出范围
Posted
技术标签:
【中文标题】二维向量下标超出范围【英文标题】:2D vector subscript out of range 【发布时间】:2014-02-11 02:32:07 【问题描述】:实现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;
【问题讨论】:
你需要is_perfect_square函数中的“地板”吗? 另外,for(int i=0; i<=hotel.size(); i++)
无效,因为您正在访问下面的hotel[i]
。下标范围仅从 0 到 hotel.size() - 1
【参考方案1】:
我把我的答案放在 cmets 中。
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;
【讨论】:
以上是关于二维向量下标超出范围的主要内容,如果未能解决你的问题,请参考以下文章