. Advertisement .
..3..
. Advertisement .
..4..
I’m building a new program, but when I run it, an error pops up. The error displayed is as follows:
'std::out_of_range' what(): vector:_M_range_check
I have tried several workarounds, but they still do not get the desired results. If you have come across this situation and have a solution for the “terminate called after throwing an instance of ‘std::out_of_range’” problem, pls let me know. Here is what I do:
#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);
}
}
Thanks!
The cause: This appears to be a typo, and you should use the variable ‘j’ in the second loop instead. Following the first loop,
Because the variable ‘i’ has the value 52, it appears that using nums.at(i) will result in a std::out of range, because nums only has 52 values, starting at index 0.
The solution: To solve this problem, you should replace the argument of at() with ‘j’
You can access
deck
elements here:But it is empty. Before making these calls, you must fill it.
std::vector::size
can be used to determine if a vector has been filled withstd::vector::empty
. For more information, see this HTML14 reference.