-
February 17th, 2012, 05:10 AM
#1
Copy 3D vector into another
Hi I have the following function:
Code:
void fillVectorWithNumbers(vector<vector<vector<double>>> &vI3)
{
const long dim1 = 10;
const long dim2 = 16;
vector<vector<vector<double>>> vI3Temp(dim1, vector<vector<double>> (dim2, vector<double> (dim2, 0.0f)));
// Do some calculation and finally fill the vector by looping over i, j and k
vI3Temp[i][j][k] = answer;
// Copy vI3Temp into vI3. How to do it?
return;
}
So basically I need to copy vI3Temp into vI3. I assume I can't loop over each element because I haven't sized vI3. So I guess I need some push_back for this. But what code to use?
Thanks.
-
February 17th, 2012, 05:25 AM
#2
Re: Copy 3D vector into another
Originally Posted by bar_ba_dos
Hi I have the following function:
Code:
void fillVectorWithNumbers(vector<vector<vector<double>>> &vI3)
{
const long dim1 = 10;
const long dim2 = 16;
vector<vector<vector<double>>> vI3Temp(dim1, vector<vector<double>> (dim2, vector<double> (dim2, 0.0f)));
// Do some calculation and finally fill the vector by looping over i, j and k
vI3Temp[i][j][k] = answer;
// Copy vI3Temp into vI3. How to do it?
return;
}
So basically I need to copy vI3Temp into vI3. I assume I can't loop over each element because I haven't sized vI3. So I guess I need some push_back for this. But what code to use?
Thanks.
Since you are using vectors, then operator= will work just fine:
Although at this point, since you know you won't be using vI3Temp, you could also just do a swap, and not pay the copy:
Or if you want to be even more clever, using C++11 and R-value references, you can move vI3Temp into vI3:
Code:
vI3 = std::move(vI3Temp);
swap and move are roughly equivalent, the differences are:
- With swap, the objects belonging to vI3 are placed into vi3Temp
- With move, the objects inside vi3 are immediately destroyed (and NOT placed inside vi3Temp))
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|