这是我的代码的一部分,是代码的唯一活动部分,其余部分已被注释掉,我正在尝试创建一个向量堆栈,该向量将板10堆高,然后创建一个新的堆栈。这是我第一次使用堆栈,因此我不知道是否正确声明了向量。
但是更重要的是,每当我尝试通过for循环将项目推入堆栈时,我都会收到一个错误:矢量下标超出范围行: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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句