ConnerLee
ConnerLee

Reputation: 27

Assign new vector to vector returned from function in C++

I have a function in C++ that takes a vector, and constructs a vector of the same size with modified values, then returns it:

vector<double> sigmoid_from_vector(vector<double> v){
    int size = (v.size());//redundant but helps
    vector<double> sigvec(size);//Create empty vector to store sigmoid values
    for (int i = 1; i<=size; i++) {
      sigvec[i] = 1/(1+exp(-1*v[i]));
      //cout << "sig val calculated: " << sigvec[i] << endl;
    }
    return sigvec;
}

I cannot, for the life of me, use the returned vector. So for I have tried the following lines, that to my knowledge should work:

vector<double> testsig = sigmoid_from_vector(age_train);
vector<double> testsig = move(sigmoid_from_vector(age_train));

edit: I should go to bed. Thank you everyone

Upvotes: 1

Views: 151

Answers (1)

user12002570
user12002570

Reputation: 1

There are several problems with you given program.

Problem 1

Since you're using i<=size instead of i<size you'll go out of bound of the vector leadingto undefined behavior.

Additionally note that vector indexing starts from 0 and not 1 so you can replace int i = 1 with int i = 0.

Problem 2

Moreover, there is no need to create a separate vector named sigvec as v is already a local copy of the passed vector.

Thus the total changes are as follows:

vector<double> sigmoid_from_vector(vector<double> v){
    
//---------------v--------------------->0 instead of 1
    for (int i = 0; i<size; i++) {
//-------------------^----------------->< instead of <=
      
        //other code here using v instead of sigvec
    }
    return v;
}

Upvotes: 4

Related Questions