[英]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
. std::vector
矩阵实际上是std::vector
的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. 我相信,您确实需要出于目的使用
pointers
。
Neurones[i]->push_back(new Neurone(new Neurone[0], new double[0]));
Why are you doing this? 你为什么做这个? What does
new Neurone[0]
means? new Neurone[0]
是什么意思? If you meant to create a Neurone
by this statement, then actually you are passing one Neurone
object to the constructor
of another. 如果要通过此语句创建
Neurone
,则实际上是将一个Neurone
对象传递给另一个对象的constructor
。
Neurones[i])[j]
will give you a pointer to Neuron . Neurones[i])[j]
将为您提供指向Neuron的指针 。 So if Neuron
class has a public member variable named Value
, you can set it by 因此,如果
Neuron
类具有一个名为Value
的公共成员变量,则可以通过以下方式进行设置
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);
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.