为什么我得到一个 "向量超出范围 "的错误?

问题描述 投票:0回答:1

当我尝试运行我的代码时,它编译得很好,但在运行时它给出了一个超出范围的向量错误。谁能帮帮我?

我在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;
}
c++ vector compiler-errors indexoutofboundsexception
1个回答
3
投票

你的代码很奇怪,你输入的是 sizeOfAnotherArray 多次,因此多次调整整个数组的大小。但是注意,你只改变了行数。你添加的每一行都会有最新的大小,但是前面的行会保持原来的大小。

这就意味着,如果你的数组中的一个后来的值 sizeOfAnotherArray 大于其中一个早期的值,那么你会得到一个超出范围的错误,因为早期的行仍然会有较小的尺寸。

我猜你想写的代码是这样的。它创建了一个 锯齿阵它是一个数组,其中列数根据你所在的行而变化。

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";
}
© www.soinside.com 2019 - 2024. All rights reserved.