[英]terminate called after throwing an instance of 'std::out_of_range' what(): array::at: __n (which is 1990878449) >= _Nm (which is 5)
array<int,5> ar3;
for(auto i : ar3){
ar3.at(i) = i+1;
cout<<ar3.at(i)<<" ";
}
cout<<endl;
The above is the piece of code that I run and the following error popped up上面是我运行的那段代码,弹出如下错误
terminate called after throwing an instance of 'std::out_of_range' what(): array::at: __n (which is 1990878449) >= _Nm (which is 5)在抛出 'std::out_of_range' what(): array::at: __n (即 1990878449) >= _Nm (即 5) 的实例后调用终止
What am I missing/going wrong on?我错过了什么/出了什么问题?
Thanks谢谢
std::array
is a plain aggregate, when you declare an instance like this, std::array
是一个普通的聚合,当你声明一个这样的实例时,
std::array<int, 5> a;
it does not initialize any of its member values.它不初始化任何其成员值。 Hence, all int
s in the array contain some random garbage values.因此,数组中的所有int
都包含一些随机垃圾值。 Next, you iterate over the values of the array,接下来,您遍历数组的值,
for (auto i : a) { /* .. */ }
The loop variable i
will hold these garbage values during the iteration, one at a time, until accessing the array out of bounds with循环变量i
将在迭代期间保存这些垃圾值,一次一个,直到访问数组越界
ar.at(i) // again: i can be anything
It seems that what you want to do is having i
increase from zero to size - 1
.看来您想要做的是让i
从零增加到size - 1
。 Use a good old for
loop for this:为此使用一个很好的旧for
循环:
for (int i = 0; i < ar3.size(); ++i)
{
ar3.at(i) = i + 1;
}
When you do:当你这样做时:
for (auto i : ar3)
it's like:就像是:
for (int x = 0; x < ar3.size(); x++) {
i = ar3.at(x);
// here the for (auto i : ar3) start
}
But you didn't initialise the value of ar3
so you have random number in it.但是你没有初始化ar3
的值,所以你有随机数。 So in your loop you try to access random case of your array
.因此,在您的循环中,您尝试访问array
随机大小写。 To fix that you can initialise your array or don't use for (auto i : ar3)
but:要解决此问题,您可以初始化数组或不使用for (auto i : ar3)
但是:
for (int i = 0; i < ar3.size(); i++) {
ar3.at() = i + 1;
}
From std::array
:从std::array
:
default initialization may result in indeterminate values for non-class T)默认初始化可能会导致非类 T 的值不确定)
This is indeed what happens for int
and reading these values makes your program have undefined behavior.这确实是int
发生的情况,读取这些值会使您的程序具有未定义的行为。
If your aim is to fill the std::array
with the values 1-5, you could instead use std::iota
:如果您的目标是用值 1-5 填充std::array
,则可以改用std::iota
:
#include <array>
#include <numeric> // std::iota
int main() {
std::array<int, 5> ar3;
std::iota(ar3.begin(), ar3.end(), 1); // start at 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.