[英]Why am I getting a “vector out of range” error?
當我嘗試運行我的代碼時,它編譯得很好,但是在運行時它給出了一個超出范圍的向量錯誤。 誰能幫我嗎?
我已經在 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
后面的值之一大於前面的值之一,那么您將得到超出范圍的錯誤,因為前面的行仍然具有較小的大小。
我猜你打算寫的代碼是這樣的。 它創建一個參差不齊的數組,該數組的列數取決於您所在的行。
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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.