为什么会发生这种情况,我的程序说它没有错误,但是当我运行它时,抛出一个'std :: out_of_range'what():vector:_M_range_check实例后,终止调用。我是C ++的新手,所以我不理解这些错误
#include <vector>
#include <iostream>
#include <random>
#include <time.h>
using namespace std;
using std::vector;
int main()
{
vector<int> deck;
vector<int> nums;
default_random_engine eng(time(0));
uniform_int_distribution<int> dis(0, 51);
int pos1;
int pos2;
int num1;
int num2;
int i;
int n;
int m;
for (i = 0; i < 52; i++)
{
nums.push_back(i);
}
for(int j = 0; j < 52; j++)
{
cout << nums.at(i) << "\n";
}
for(n = 0; n < 50; n++)
{
pos1 = dis(eng);
pos2 = dis(eng);
cout << pos1 << "\n" << pos2 << "\n";
num1 = deck.at(pos1);
num2 = deck.at(pos2);
}
}
在我看来,这似乎是由于拼写错误所致,您应该在第二个循环中使用变量“ j”。在第一个循环之后,
for (i = 0; i < 52; i++)
{
nums.push_back(i);
}
变量'i'包含值52,因此听起来像是调用nums.at(i)会引发std :: out_of_range,因为nums仅包含52个值,从索引0开始。
for(int j = 0; j < 52; j++)
{
cout << nums.at(i) << "\n";
}
通过将at()的参数替换为'j'来解决此问题,我认为这是原始意图:
for(int j = 0; j < 52; j++)
{
cout << nums.at(j) << "\n";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句