IMI
IMI

Reputation: 105

Copy a vector to an array?

I copied a 2dim array into a 2dim vector and I did some modifications on it, now i want to know how can I copy a 2dim vector into a 2dim array?(I did as below:)

Copy an 2dim array to 2dim vector:

vector< vector<int>> path2;
 vector<int> temp; // For simplicity
 for (int x = 0; x <= 1; x++)
{temp.clear();
    for (int y = 0; y < 4; y++)
    {
        temp.push_back(path1[x][y]);
    }
    path2.push_back(temp);

}

out put:

path2[0][6,0,2,6]
path2[1][6,1,3,6]

Copy the 2dim vector to 2dim array

int arr [4][10] ;
 copy(path3.begin(), path3.end(), arr);

print the arr

 for (int i=0;i< ???? ;i++)// how to define size of the vector first dimention which is 2 ( i am aware about size() for 1 dim vector, but for 2dim vector ...... ??????????
     for(int j=0;j<?????; j++) //same prolem as above
         cout<<endl<<arr[i][j];

The problem is i am not sure about the copy part and and i dont know how to define the size of each size of vector?

Upvotes: 0

Views: 140

Answers (1)

MS Srikkanth
MS Srikkanth

Reputation: 4241

You could do any of these to iterate over a vector of vector:

//Works for C++11
std::vector<std::vector<int>> vec;
for(auto &i : vec)
   for(auto &j : i)
      std::cout << j << std::endl;

//Works for C++11
for (auto iter = vec.cbegin(); iter != vec.cend(); ++iter)
    for(auto sub_iter = iter->cbegin(); sub_iter != iter->cend(); ++sub_iter)
       std::cout << *sub_iter << std::endl;

//Works for C++03 and C++11
typedef std::vector<std::vector<int> >::iterator Iter;
typedef std::vector<int>::iterator Sub_Iter;
for (Iter iter = vec.begin(); iter != vec.end(); ++iter)
    for(Sub_Iter sub_iter = iter->begin(); sub_iter != iter->end(); ++sub_iter)
       std::cout << *sub_iter << std::endl;


//works for C++03 and C++11
for(int i = 0; i<vec.size(); ++i)
    for(int j = 0; j < vec[i].size(); ++j)
       std::cout << vec[i][j] << std::endl;

Upvotes: 4

Related Questions