gpt4 book ai didi

c++ - 更改原始 vector 不会在集合中更改它

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:57:01 24 4
gpt4 key购买 nike

为什么我得到不同的输出?我怎样才能解决这个问题?我希望 trainingVector[0] 引用 A。

vector<double> A(4,0);
vector<vector<double > > trainingVector;
A[0]=1;
trainingVector.push_back(A);
A[0]=2;
cout << A[0] << endl ;
cout << trainingVector[0][0] << endl ;

最佳答案

您不能在 STD 容器中存储引用,因此您所要求的是不可能的。如果您希望 trainingVector 存储指向 A指针,这是完全可行的:

vector<double> A(4,0);
vector<vector<double>*> trainingVector;

A[0] = 1;
trainingVector.push_back(&A);
A[0] = 2;

// notice that you have to dereference trainingVector[0] to get to A
cout << (*trainingVector[0])[0] << endl; // prints 2

关于c++ - 更改原始 vector 不会在集合中更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8350170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com