Vector of vectors function

closed account (9ST04iN6)
I am trying to declare a function that will return a vector of vectors but I do not know how to declare it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <vector>
#include <iostream>

using std::vector;

// Creates 3 outer arrays,
// each having an inner array with 5 elements,
// all initialized to 42
vector<vector<int>> createThingy()
{
    return vector<vector<int>>(3, vector<int>(5, 42));
}

int main()
{
    vector<vector<int>> thing = createThingy();
    std::cout << thing[1][0] << '\n';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <vector>
#include <iostream>
using namespace std;

using matrix = vector< vector<int> >;

matrix reshape( int m[], int rows, int cols )
{
   matrix M( rows, vector<int>( cols ) );
   for ( int i = 0, p = 0; i < rows; i++ )
   {
      for ( int j = 0; j < cols; j++ ) M[i][j] = m[p++];
   }
   return M;
}

int main()
{
   int a[] = { 1, 2, 3, 4, 10, 20, 30, 40, 100, 200, 300, 400 };
   matrix A = reshape( a, 3, 4 );
    
   for ( auto &row : A )
   {
      for ( auto e : row ) cout << e << '\t';
      cout << '\n';
   }
}

1	2	3	4	
10	20	30	40	
100	200	300	400	
Last edited on
Topic archived. No new replies allowed.