Vector::push_back不在Vector中存储值

Vector::push_back not storing values in vector

本文关键字:Vector 存储 back push 不在      更新时间:2023-10-16

最近我一直在尝试写一个神经网络程序。我将所有的神经元连接存储在神经元的向量中。然而,每当我将连接推回向量时,它似乎不会存储(我可以通过调试模式来判断),并且当我试图在for循环中添加向量的激活值时,我就会得到out_of_range错误。这是我的代码。

Main.cpp

#include <iostream>
#include "neuron.h"
void displayboard(bool board [8][8]);
using namespace std;
int main()
{
    int id = 2;
    int inputids [] = {3};
    int outputids [] = {4};
    int inputweights [] = {5};
    bool new_neuron = true;
    neuron test (inputids, outputids, inputweights, new_neuron, id);
    test.connections.at(0).value = 6;
    // here is where the error is returned
    test.activation();
    cout << test.activationnumber;
    return 0;
}

这里是neuron。cpp:

#include "neuron.h"
#include <vector>
#include <random>
#include <ctime>
using namespace std;
neuron::neuron(int inputids [], int outputids [], int inputweights [], 
    bool new_neuron, int id)
{
    this->id = id;
    if (new_neuron==true) {
        srand (time(0));
        connection tempconnection;
        for (int i = 0; i <=(sizeof (inputids)/sizeof (inputids [0])); i++)            
        {
            tempconnection.type=false;
            tempconnection.tofrom = inputids [i];
            tempconnection.weight = rand ();
            this->connections.push_back (tempconnection);
        }
    // this continues on for other options
}
void neuron::activation (){
    for (int i=0; i<=this->connections.size (); i++) {
        this->activationnumber += ((this->connections.at(i).value)
            *(this->connections.at (i).weight));
    }
}

UPDATE:阅读这篇文章将帮助你理解为什么你的"sizeof/sizeof"方法在c++中不是很好。


原始回答

sizeof(array)/sizeof(array[0])的行为可能不是你所期望的。下面的代码输出2,但您似乎期望输出4。对于堆栈中的对象使用array,对于堆中的对象使用vector。

#include <iostream>
using namespace std;
void foo( int array[] )
{
    wcout << sizeof( array ) / sizeof( array[ 0 ] );
}
int main()
{
    int test[ 4 ];
    foo( test );
    return 0;
}

改变
int inputids [] = {3};
int outputids [] = {4};

vector< int > {3};
vector< int > {4};

也改变

neuron(int inputids [],int outputids [] …
{
    …
    for (int i = 0; i <= …; i++)            
        …
        tempconnection.tofrom = inputids [i];

neuron( vector< int > & inputids, vector< int > & outputids …
{
    …
    for( auto id : inputids )
        …
        tempconnection.tofrom = id;