将vector作为对象从一个类传递到另一个类

passing vector from one class to other as object

本文关键字:一个 另一个 vector 对象      更新时间:2023-10-16

我有两个类NetGA,我想通过main将一个向量从GA传递到Net。考虑下面的代码:

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) );
}

错误是:

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>&’

任何想法?

这很简单:根据标准,只有const引用可以绑定到临时对象。

g.get_chromosome(chromo)返回一个临时对象,Net::setWeights(vector <double> &wts)尝试用常规引用绑定到它。

如果你不打算改变向量,Network::setWeights(std::vector<double>& wts)应该是Network::setWeights(const std::vector<double>& wts),或者Network::setWeights(std::vector<double> wts)如果你做。

最后一个选项是移动向量,在这种情况下,您应该使用移动语义

如果不知道如何声明population,我会说change return population[I];对于返回种群;在get_chromosome

我创立了答案。实际上,问题是与网络接收端的参考有关。你不需要这个;如果你不改变向量。@ david是对的。

考虑下面的例子:

#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;
}

输出为:

20
10
相关文章: