抛出'std :: out_of_range'实例后调用终止

时间:2013-10-07 04:30:19

标签: c++ c++11

为什么会发生这种情况我的程序说它没有错误但是当我运行它时我会在抛出'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);

}

}

2 个答案:

答案 0 :(得分:12)

它看起来好像这是由于拼写错误,你应该在第二个循环中使用变量'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";
}

通过将'(')的参数替换为'j'来修复它,我认为这是原始意图:

for(int j = 0; j < 52; j++)
{
    cout << nums.at(j) << "\n";
}

答案 1 :(得分:3)

您可以访问deck中的元素:

num1 = deck.at(pos1);
num2 = deck.at(pos2);

但它是空的。在拨打电话之前,你必须在某个时候填写它。您可以使用std::vector::empty方法检查向量是否为空,并使用std::vector::size获取其大小。有关这两种方法的更多信息,请参阅此std::vector reference

相关问题