Disdaining
Disdaining

Reputation: 23

passing vector from one class to other as object

I have two classes Net and GA and I want to pass a vector from GA to Net through main. Consider the following code.

class GA {
    inline vector <double> get_chromosome(int i) { 
        return population[i]; 
    }
}

class Net {
    int counter;
    Net::setWeights(vector <double> &wts){
        inpHidd = wts[counter];
    }
}

main(){
    net.setWeights( g.get_chromosome(chromo) );
}

Error is:

Network.h:43:8: note: void Network::setWeights(std::vector<double>&)
   void setWeights ( vector <double> &wts );
        ^
Network.h:43:8: note:   no known conversion for argument 1 from ‘std::vector<double>’ to ‘std::vector<double>&’

Any Idea?

Upvotes: 1

Views: 582

Answers (3)

David Haim
David Haim

Reputation: 26496

This is simple: according to the standard, only const references can bind to temporaries.

g.get_chromosome(chromo) returns a temporary, and Net::setWeights(vector <double> &wts) tries to bind into it with regular reference.

The line Network::setWeights(std::vector<double>& wts) should be Network::setWeights(const std::vector<double>& wts) if you're not going to change the vector, or Network::setWeights(std::vector<double> wts) if you do.

One last option is to move the vector around, in this case you should use move semantics.

Upvotes: 1

Disdaining
Disdaining

Reputation: 23

I founded the Answer. Actually the problem is with the reference on the receiving end in Net. You don't need that; if you are not changing the vector. @Dvid is right.

Consider the following example:

#include <iostream>
using namespace std; 
void addone (int &x){
    x = x + 10; 
}

void addtwo(int x){
    x = x + 10; 
}

int main (){    
int x = 10; 
addone(x);
cout<<x; 
int y = 10;
addtwo(y);
cout<<endl<<y;
}

Output is:

20
10

Upvotes: 0

exs
exs

Reputation: 122

Without knowledge on how population is declared, I would say to change return population[i]; for return population; in get_chromosome

Upvotes: 0

Related Questions