[当我尝试运行我的代码时,它可以很好地编译,但是在运行时,它会给出超出范围的矢量错误。谁能帮帮我?
我已经用Xcode编写了代码:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int numOfRows = 0;
cout << "Enter number of rows: ";
cin >> numOfRows;
vector<vector<int>> vec;
int sizeOfAnotherArray = 0;
int value = 0;
for (int i = 0; i < numOfRows; i++) {
cout << "Enter size of another array: ";
cin >> sizeOfAnotherArray;
vec.resize(numOfRows,vector<int>(sizeOfAnotherArray));
for (int j = 0; j < sizeOfAnotherArray; j++) {
cout << "Store Value: ";
cin >> value;
vec.at(i).at(j) = value;
}
}
for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < sizeOfAnotherArray; j++) {
cout << vec.at(i).at(j) << " ";
}
cout << "\n";
}
return 0;
}
关于代码的奇怪之处在于,您多次输入sizeOfAnotherArray
,因此会多次调整整个数组的大小。但是请注意,您仅更改了行数。您添加的每一行都将具有最新大小,但较早的行将保留其原来的大小。
这意味着,如果sizeOfAnotherArray
的较新值之一大于较早的值之一,那么您将得到超出范围的错误,因为较早的行仍将具有较小的大小。