I have a vector containing something like
{1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 }
So the vector represent the columns of an upper right matrix
1 2 4 7
0 1 5 8
0 0 1 9
0 0 0 1
How could I use the vector and get from
{1, 2, 1, 4, 5, 1, 7, 8 ,9, 1 }
to
1 2 4 7
2 1 5 8
4 5 1 9
7 8 9 1
as a vector
{ 1,2,4,7,
2,1,5,8,
4,5,1,9,
7,8,9开发者_开发问答,1 }
In fact After reviewing the code, the solution is:
for (int i = 0; i < cols; ++i)
for (int j = 0; j <= i; ++j)
v[cols * i + j] = v[cols * j + i] = w[k++];
int k=0;
for(int i = 0; i<4; ++i)
for(int j = 0; j<=i; ++j)
v[i][j]=v[j][i]=w[k++];
Assuming source vector is w, dest is v.
If it should be 1D, not 2D, then [i][j]
should be changed to [4*i+j]
.
EDIT This can be done 'in-place', but it is a little tricky. In order not to overwrite values you haven't used yet, you have to loop backwards and to make two passes:
int k=10;
for(int i = 3; i >=0; --i)
for(int j = i; j >= 0; --j)
v[4*i+j]=v[--k];
for(int i = 0; i < 4; ++i)
for(int j = 0; j < i; ++j)
v[4*j+i]=v[4*i+j];
精彩评论