为什么我将矢量下标出范围超出范围

Why am I getting vector subscript out of range?

本文关键字:范围 下标 为什么      更新时间:2023-10-16

这是我代码的一部分,现在是其余部分的唯一活动部分,因为其余部分被评论出来,我正在尝试创建一个堆栈的堆栈向量然后创建一个新的堆栈。这是我第一次真正使用堆栈,所以我不知道我是正确声明了矢量还是其他。

,但更重要的是,每当我尝试通过for循环将项目推到堆栈上时,我会收到一个错误:vector subscript超出范围行:1234,我不确定我应该如何推到堆栈或有一种使用trains.push_back()的方法。(每次我尝试push_back,我都会遇到错误)。

#include <stack>
#include <iostream>
using namespace std;

int main()
{
vector<stack<int>> plates;
int numPlates,plateColor;
int x = 0;
cout << "Enter number of Plates" << endl;
cin >> numPlates;
for (int i = 0; i < numPlates; i++) {
    if ((x + 1) % 10 == 0) // once plates are stacked ten high, start new stack
        x++;
    cin >> plateColor;
    plates[x].push(plateColor);
}

您需要创建堆栈,填充它,然后使用emplace_back将其添加到向量中。这样的事情应该有效:

for ( int i = 0; i < numPlates; i += 10 ) 
{
    stack<int> temp = stack<int>();
    for ( int j = 0; j < 10 && j + i < numPlates; j++ );
    {
        int plateColor = 0;
        cin >> plateColor;
        temp.push( plateColor );
    }
    plates.emplace_back(temp);
}

当x为0时,或每当x增量时,您需要将新堆栈推入板上[x]