简体   繁体   中英

C++ CodeBlock Issue With Vector In Array

I'm unable to modify a vector inside the vector array using CodeBlock 20.03. Here's the "reduced" version of code:

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;

vector<int> neighbor_fields[500000];
int main()
{
    neighbor_fields[0].push_back(0);

    return 0;
}

The program runs fine, but there's an error displayed after program finishes "Terminated with status -1073741510" . I've done some research and this script seems like it is perfectly legal in C++.

I think is is an issue related to CodeBlock/compiler(gcn gcc) because it compiles fine on elsewhere.

Thanks.

EDIT: I've corrected the code(it should be an array of vectors instead of a single vector). Another interesting thing is doing a push_back on a single vector also terminates with that error code:

#include <iostream>
#include <vector>
#include <stdio.h>

using namespace std;

vector<int> neighbor_fields;
int main()
{
    neighbor_fields.push_back(0);
    return 0;
}

As shown in cppreference:vector operator[] , accessing a nonexistent element through this operator is undefined behavior.

For your case, neighbor_fields[0] means that it access the first element of the vector, which is nonexistent and resulting in the error.

it should be: neighbor_fields.push_back(0);

there are 2 misunderstanding in this code:

  1. when you declare neighbor_fields you create a container but you are not putting anything in it. So if you try to access to an item of the container you are gonna get an undefined behavior, if you want to make the program safer you can use std::vector::at , it works like std::vector::operator[] but when the index is out of range throw an exeption so you can handle it.

  2. std::vector::operator[] return a reference to a variable of the type stored by the container, in our case int , you can not use push_back() on a int variable but you use it for adding items at the container. The code you are looking for is

    std::vector neighbor_fields;

    int main() {

     neighbor_fields.push_back(0); return 0;

    }

this code create a container and add the value 0. You can assume that a std::vector is like a c-like arrays so int array[10] , but is possible change the size adding and erasing items.

I'm sorry for the code but I can't mark it us code

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