CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Mar 2007
    Posts
    20

    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.

  2. #2
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Copy 3D vector into another

    Quote Originally Posted by bar_ba_dos View Post
    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:

    Code:
    vI3 = vI3Temp;
    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:

    Code:
    vI3.swap(vI3Temp);
    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
  •  





Click Here to Expand Forum to Full Width

Featured