C++ 抛出“std::out_of_range”实例后调用终止
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19217093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
terminate called after throwing an instance of 'std::out_of_range'
提问by Costas Vrahimis
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
为什么会发生这种情况,我的程序说它没有错误,但是当我运行它时,我在抛出一个 '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);
}
}
回答by Martin 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,
在我看来,这是由于打字错误造成的,您应该在第二个循环中使用变量“j”。第一次循环后,
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.
变量“i”包含值 52,因此听起来预期调用 nums.at(i) 会抛出 std::out_of_range,因为 nums 仅包含 52 个值,从索引 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:
通过将 at() 的参数替换为 'j' 来修复它,我认为这是原始意图:
for(int j = 0; j < 52; j++)
{
cout << nums.at(j) << "\n";
}
回答by juanchopanza
You access elements in deck
here:
您可以访问deck
此处的元素:
num1 = deck.at(pos1);
num2 = deck.at(pos2);
but it is empty. You have to fill it at some point before making those calls. You can check if a vector is empty with the std::vector::empty
method, and get it's size with std::vector::size
. See this std::vector
referencefor more information on those two methods.
但它是空的。在拨打这些电话之前,您必须在某个时候填写它。您可以使用该std::vector::empty
方法检查向量是否为空,并使用std::vector::size
. 有关这两种方法的更多信息,请参阅此std::vector
参考资料。