简体   繁体   中英

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?

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 .

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

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

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