Mehdi Tanhatalab
Mehdi Tanhatalab

Reputation: 55

Copying a "vector of vector" into" array of array"

First I had an int array called Myarray[51][4] filled by data.

For sorting it based on the second column of Myarray, I used the following code (using the conversion of array into a vector of vector: my_vector[51][4]) :

int Myarray [51][4];
vector< vector<int> > my_vector ;
for( const auto& row : Myarray ) 
    my_vector.push_back( vector<int>( begin(row), end(row) ) ) ;

sort( begin(my_vector), end(my_vector),
       []( const vector<int>& a, const vector<int>& b ) { return a[1] < b[1] ; } ) ;

This code has sorted my_vector. Now I want to copy the sorted vector into Myarray again for using it as array of integer with dimension of [51][4]. How do I do it?

Upvotes: 0

Views: 212

Answers (1)

sasha.sochka
sasha.sochka

Reputation: 14715

The simplest and the most obvious one:

for (size_t row = 0; row < my_vector.size(); ++row) {
  for (size_t col = 0; col < my_vector[row].size(); ++col) {
    Myarray[row][col] = my_vector[row][col];
  }
}

Or another solution without the inner loop:

for (size_t row = 0; row < my_vector.size(); ++row) {
  copy(my_vector[row].begin(), my_vector[row].end(), Myarray[row]);
}

But better stop using C-style arrays in C++ and switch to std::vector or std::array completely!

For your request in the comment here is an example with std::vector:

vector<vector<int>> my_vector =  {{3, 8, 7, 2}, {9, 12, 0, 4}, {12, 2, 14, 1}};
sort(begin(my_vector), end(my_vector),
     [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; }
) ;

Upvotes: 4

Related Questions