【问题标题】:Why am I getting a "vector out of range" error?为什么会出现“向量超出范围”错误?
【发布时间】:2020-08-20 23:52:24
【问题描述】:

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

我已经在 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】:

    您的代码的奇怪之处在于您多次输入 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";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-07
      • 2016-08-22
      • 2019-01-24
      • 2017-12-02
      • 1970-01-01
      • 2019-02-13
      相关资源
      最近更新 更多