为什么会出现“向量超出范围”错误?

时间:2020-05-06 05:33:27

标签: c++ vector compiler-errors indexoutofboundsexception

当我尝试运行代码时,它可以很好地编译,但是在运行时,它会给出超出范围的矢量错误。有人可以帮我吗?

我已经用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;
}

1 个答案:

答案 0 :(得分:3)

关于代码的奇怪之处在于,您多次输入sizeOfAnotherArray,因此多次调整整个数组的大小。但是请注意,您仅更改行数。您添加的每一行都将具有最新大小,但较早的行将保留其原来的大小。

这意味着,如果sizeOfAnotherArray的较新值之一大于较早的值之一,则将出现超出范围的错误,因为较早的行的大小仍然较小。 / p>

我猜想您打算编写的代码就是这样。它会创建一个参差不齐的数组,该数组中的列数根据您所在的行而有所不同。

cout << "Enter number of rows: ";
cin >> numOfRows;
vector<vector<int>> vec(numRows); // create array with N rows

for (int i = 0; i < numOfRows; i++) {
    cout << "Enter size of another array: ";
    cin >> sizeOfAnotherArray;
    vec.at(i).resize(sizeOfAnotherArray); // resize this row only
    for (int j = 0; j < sizeOfAnotherArray; j++) {
        ...
    }

for (int i = 0; i < vec.size(); i++) {
    for (int j = 0; j < vec.at(i).size(); j++) { // loop on the size of this row
        cout << vec.at(i).at(j) << " ";
    }
    cout << "\n";
}