Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terminate called after throwing an instance of 'std::out_of_range'

Tags:

c++

c++11

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);

}

}
like image 407
Costas Vrahimis Avatar asked Oct 07 '13 04:10

Costas Vrahimis


1 Answers

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);
}

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";
}

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";
}
like image 110
Martin J. Avatar answered Sep 18 '22 20:09

Martin J.