Reputation: 1056
I am having trouble converting type vector< vector > to an array.So far, I've tried to do the following (with help from /u/ Robert Crovella)
pos_x_h=(double *)malloc(N*sizeof(double));
pos_y_h=(double *)malloc(N*sizeof(double));
for (int i = 0; i<N; i++){
vector<double> temp = r[i];
pos_x_h[i] = temp[i][0];
pos_y_h[i] = temp[i][1];
}
Here, r is the position vector with N elements each having x and y components. I also tried doing
double arr[N];
std::copy(r.begin(), r.end(), arr);
Both attempts didn't work, and I'm not sure why. You can see the code here.
Upvotes: 0
Views: 70
Reputation: 46435
The following ought to work. Note that I prefer sizeof *pos_x_h
over sizeof(double)
since the former makes sure the size is correct even if you change the type of the variable (which might be in another piece of code). updated* for C++ you need to cast the result of malloc
. I was thinking with my C hat on...
second update
A bit more thought tells me you really don't want to have temp
as a vector - that is just making things more confusing. Instead, point to the address of the first element of r[i]
: this compiles without errors
pos_x_h=(double *)malloc(N*sizeof(double));
pos_y_h=(double *)malloc(N*sizeof(double));
for (int i = 0; i<N; i++){
double* temp;
temp = &r[i][0];
pos_x_h[i] = temp[0];
pos_y_h[i] = temp[1];
}
Of course you could simply do
pos_x_h=(double *)malloc(N*sizeof(double));
pos_y_h=(double *)malloc(N*sizeof(double));
for (int i = 0; i<N; i++){
pos_x_h[i] = r[i][0];
pos_y_h[i] = r[i][1];
}
and avoid the whole mess.
Upvotes: 2