I am currently learning c++ and was trying to write code that will find the minima of a function. I have put my starting points in vectors p0,p1,p2 and stored those set of points in a vector which I have called pmatrix.
I am trying to pass this pmatrix as an argument when I am creating an object of the simplex class. When I wrote the code below my hope was that I had correctly passed the pmatrix, by reference, into the constructor properly as no errors came up.
However, after calling the evaluate method which changes pmatrix, printing the values inside and outside of the class definition, it has not changed in the main scope and somewhere 2 separate copies of pmatrix exist. How do I make sure that the changes the methods do to pmatrix act on the one I have defined in the main scope?
#include <iostream>
#include <vector>
class Simplex {
std::vector<std::vector<double>> pmatrix;
double (*F)(double x_0,double x_1);
public:
Simplex(std::vector<std::vector<double>> &pmatrix,double (*func)(double,double)){
this->pmatrix = pmatrix;
F=func;
}
void evaluate(){
for (int i=0; i<pmatrix.size();i++){
std::vector<double> p_i;
p_i=pmatrix[i];
p_i[p_i.size()-1]=F(p_i[0],p_i[1]);
pmatrix[i]=p_i;
}
}
void test(){
std::cout<<"pmatrix[i][2] elements inside the class def is "<<pmatrix[0][2]<<" "<<pmatrix[1][2]<<" "<<pmatrix[2][2]<<"\n";
}
};
//defining rosenbrocks parabolic valley
double rpv (double x1, double x0){
return 100*(x0-(x1*x1))*(x0-(x1*x1))+(1-x0)*(1-x0);
}
int main()
{
std::vector<double> p0 = {0,0,1};
std::vector<double> p1 = {2,0,2};
std::vector<double> p2 = {0,2,3};
std::vector<std::vector<double>> pmatrix = {p0,p1,p2};
Simplex simplex(pmatrix,rpv);
simplex.evaluate();
std::cout<<"pmatrix[i][2] elements from pmatrix in main "<<pmatrix[0][2]<<" "<<pmatrix[1][2]<<" "<<pmatrix[2][2]<<"\n";
simplex.test();
return 1;
}
output
pmatrix[i][2] elements from pmatrix in main 1 2 3
pmatrix[i][2] elements inside the class def is 1 1601 401
struct Point { int x, y, z; }and then havestd::vector<Point>.using PointsMatrix = std::vector<Point>to make it even tidier!Point.push_back()? It doesn't make sense.