抛出'std :: out_of_range'实例后调用终止 [英] terminate called after throwing an instance of 'std::out_of_range'
问题描述
为什么会发生这种情况,我的程序说它没有错误,但是当我运行它时,在抛出一个'std :: out_of_range'what():vector:_M_range_check实例后,我叫终止.我是c ++的新手,所以我不理解这些错误
Why does this happen my program says that it has no errors but then when I run it I get terminate called after throwing an instance of 'std::out_of_range' what(): vector:_M_range_check. I am new to c++ so I don't understand these errors
#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'.在第一个循环之后,
It looks to me as if this is due to a typo, and you should use the variable 'j' in the second loop. After the first loop,
for (i = 0; i < 52; i++)
{
nums.push_back(i);
}
变量'i'包含值52,因此听起来像是调用nums.at(i)会抛出std :: out_of_range,因为nums仅包含52个从索引0开始的值.
the variable 'i' contains the value 52, so it sounds expected that calling nums.at(i) would throw a std::out_of_range, since nums only contains 52 values, starting at index 0.
for(int j = 0; j < 52; j++)
{
cout << nums.at(i) << "\n";
}
通过将at()的参数替换为"j"来修复它,我认为这是原始意图:
Fix it by replacing the argument of at() with 'j', which I assume was the original intent:
for(int j = 0; j < 52; j++)
{
cout << nums.at(j) << "\n";
}
这篇关于抛出'std :: out_of_range'实例后调用终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!