How to access elements of a vector of a type defined by struct?

Asked

Viewed 172 times

1

In my code, I made the following statement of struct:

struct material {
    int idmaterial;
    double rho;
    double precokg;
};

I wanted to run this function, which reads data from a file:

std::vector<material> le_material(std::string s)
{
    std::ifstream dados(s);
    dados.exceptions(std::ios::failbit |
            std::ios::badbit);

    int N{0};
    bool fim;
    std::vector<material> infomaterial;
    fim = dados.eof();

    while (fim == 0) {
        dados >> infomaterial[N].idmaterial;
        dados >> infomaterial[N].rho;
        dados >> infomaterial[N].precokg;
        N++;
        fim = dados.eof();
    }

    return infomaterial;
}

In this file, whose name is given as a function parameter, there is the information of each material. In each line there are 3 numbers, with the data to be read.

However, when running the code and executing this function in main, it gives segmentation failure.

From what I was able to explore, the error occurs at the moment when trying to pass the data from the file to a vector element of type "material". I came to think that it was an error in reading the file, but if I try to read something that I insert in the terminal, although it is possible to insert the value, also occurs the segmentation failure, soon after the insertion.

I believe that the error should be in the way I am trying to access an element of the vector, but searching on could not find anything very enlightening.

  • You probably need to allocate the space in the vector before using it, like: std::vector<material> infomaterial(10); (for 10 elements), or insert each element with Insert

  • 1

    Ah, that’s right, thank you! I thought it was more complicated than that, but now I can read it like this: 1) I declare a material type variable, mat_lido. 2) No while, I read like this: data >> mat_lido.idmaterial; data >> mat_lido.Rho; data >> mat_lido.precokg; infomateriais.push_back(mat_lido); Now I’m having problems with the moment the program should finish reading, but I’m creating another topic about it.

1 answer

1

Segmentation failure error happens when trying to change vector data infomaterial without initializing it with elements (the vector is "empty").

The solution is to initialize the vector with a predetermined number of elements:

// Exemplo para 100 elementos
std::vector<material> infomaterial(100);

Or use, for example, the method Insert or push_back before reading a file element:

material m = { 0, 0.0, 0.0 }; // Declara um elemento 'default'
fim = dados.eof();

while (!fim) {
  infomaterial.push_back(m); // Insere um novo elemento antes de ler os dados
  dados >> infomaterial[N].idmaterial;
  std::cout << infomaterial[N].idmaterial << std::endl;
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.