简体   繁体   中英

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)

What am I missing/going wrong on?

Thanks

std::array is a plain aggregate, when you declare an instance like this,

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. 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

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 . Use a good old for loop for this:

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. So in your loop you try to access random case of your array . To fix that you can initialise your array or don't use for (auto i : ar3) but:

for (int i = 0; i < ar3.size(); i++) {
    ar3.at() = i + 1;
}

From std::array :

default initialization may result in indeterminate values for non-class T)

This is indeed what happens for int and reading these values makes your program have undefined behavior.

If your aim is to fill the std::array with the values 1-5, you could instead use 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM