简体   繁体   中英

c++ vector allocation error segmentation fault

i'm trying to use a matrix of vectors declared like this :

vector<vector<Neurone*>* > Neurones;

I have already created a class Neurones by the way.

this is the code :

NeuralNetwork::NeuralNetwork(vector<int> NeuroneNumbers, vector<vector<vector<double>* >* > lw)
    {

        for (int i = 0; i < NeuroneNumbers.size(); i++)
        {
            if (i == 0)
            {
                Neurones.push_back(new vector<Neurone*>());
                for (int j = 0; j < NeuroneNumbers[i]; j++)
                {
                    Neurones[i]->push_back(new Neurone(new Neurone[0], new double[0]));
                    if (j == NeuroneNumbers[i] - 1)
                    {  
                        (*Neurones[i])[j]->Value = 1;//Here is the error ! with i=0 j=0 segmentation fault !

                    }
                }
            }}

A matrix of std::vector is actually a std::vector of std::vector .

Here is an example:

#include <iostream>
#include <vector>

int main() {
  // this is actually a 2D "array"
  std::vector< std::vector<int> > v;
  int N = 5; // rows
  int M = 5; // columns
  v.resize(N); // create N rows
  for(int i = 0 ; i < N ; ++i)
    for(int j = 0 ; j < M ; ++j)
      v[i].push_back(j); // fill the matrix

  //print
  for(int i = 0 ; i < N ; ++i)
    for(int j = 0 ; j < M ; ++j)
      std::cout << v[i][j] << "\n";

  return 0;
}

[EDIT]

I believe, that you do need to use pointers for your purpose.

 Neurones[i]->push_back(new Neurone(new Neurone[0], new double[0]));

Why are you doing this? What does new Neurone[0] means? If you meant to create a Neurone by this statement, then actually you are passing one Neurone object to the constructor of another.

Neurones[i])[j] will give you a pointer to Neuron . So if Neuron class has a public member variable named Value , you can set it by

Neurones[i])[j]->Value = 1; // no need the * operator

However, you are using pointers unnecessarily, and the usage is error prone. Your code can be greatly simplified:

vector<vector<Neurone*> > Neurones;

NeuralNetwork::NeuralNetwork(vector<int> NeuroneNumbers, vector<vector<vector<double>* >* > lw)
{

    for (int i = 0; i < NeuroneNumbers.size(); i++)
    {
        if (i == 0)
        {
            vector<Neurone*> neuronVector;
            for (int j = 0; j < NeuroneNumbers[i]; j++)
            {
                Neurone neuron=new Neurone(/*constructor params*/); // create a Neuron object
                if (j == NeuroneNumbers[i] - 1)
                {  
                    neuron.Value = 1;
                }
                neuronVector.push_back(neuron);
            }
            Neurones.push_back(neuronVector);
        }}

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