I want to construct two 2D vectors to which I can add vectors to in the future. However, even the beginning attempt to push_back a 1D vector as the first row of a 2D vector doesn't give the results I expect. THe following shows my code which attempts to construct two 2D vectors (i.e., R_pl and T_pl) and add one vector to each in the 0th row position. I fully expect my code to give a result for R_pl which only has elements in R_pl[0] (or for T_pl, elements in T_pl[0]), but I do not find this. THe following shows the code I am using:
#include <iostream>
#include <vector>
usingnamespace std;
int main(int argc, char** argv){
float R_pl_initial;
int nr;
nr=3000;
R_pl_initial=30.0;
double dr = (R_pl_initial)/(nr-1);
float T_max=165.0;
float T_min=1.0e-9;
double LB=1.0e-9;
double dT=(T_max-T_min)/(nr-1);
vector <vector<double>> R_pl;
vector <double> newrow(nr); //vector I want to push back into R_pl and T_pl as an initialization vector. This newrow I want to be the first row as it were of the 2D matrix of rows. I set its length to nr which is 3000.
cout<<"size"<< newrow.size()<<endl; //this is 3000 as expected
R_pl.push_back(newrow); //does this make R_pl have 3000 elements initialized in R_pl[0]?
for (int i1=0; i1<newrow.size(); i1++){
if (i1==0){
R_pl[0].push_back(LB);
cout<<"rplsize"<<(R_pl[0]).size()<<endl;
}
else
R_pl[0].push_back(LB+(i1*dr));
}
vector <vector<double>> T_pl;
T_pl.push_back(newrow);
for (int i2=0; i2<newrow.size(); i2++){
if (i2==0){
T_pl[0].push_back(LB);
cout<<"tplsize"<<(T_pl[0]).size()<<endl;
}
else
T_pl[0].push_back(LB+(i2*dT));
}
printf("printing tpl %lf\n", T_pl[0][1000]);
return 0}
I have two questions. First, why is it that running 'cout<<"rplsize"<<(R_pl[0]).size()<<endl;' in the code gives 3001 for the size instead of the expected 3000 from pushing in the newrow into R_pl[0]? Second, why is it that 'printf("printing tpl %lf\n", T_pl[0][1000]);' gives 0.0 for the temperature element, when it should be some value greater than zero but below 165?
1) Please put [code][/code] tags around your code in the future so it is formatted/indented nicely.
2) Your size becomes 3001 because when you construct the vector with a size that means it has 3000 intialized elements in it like you said. Then when you push_back, this creates a new element and appends it to the end, so now you have 3001 elements.
3) Printing T_pl[0][1000] gives 0.0 because the 1000th element in the first row of T_pl is 0.0 since that is was was in newrow.
Can you like not ignore @firedraco's first point? Use code tags, people are much less likely to help you if you dont use them, people like me, because I can't read the code.
If you want to modify an existing element, use the array syntax [] or the member function at() - you must specify the subscript of the element you want to access.