Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to specify the dimensions of a nested STL vector C++?

Tags:

c++

stl

vector

I know vectors can be constructed to a predefined size

vector<int> foo(4);

But is there a way to specify the dimensions of nested vectors?

vector< vector<int> > bar(4);

Lets say I wanted a vector of size 4 containing vector's of size 4... like a 4x4 multidimensional array of ints?

like image 531
zebraman Avatar asked Apr 19 '10 07:04

zebraman


2 Answers

The second argument to that constructor is the value to initialize with. Right now you're getting 4 default-constructed vectors. To clarify with a simpler 1D example:

// 4 ints initialized to 0
vector<int> v1(4);

// *exactly* the same as above, this is what the compiler ends up generating
vector<int> v2(4, 0); 

// 4 ints initialized to 10
vector<int> v3(4, 10); 

So you want:

vector< vector<int> > bar(4, vector<int>(4));
//              this many ^   of these ^

This creates a vector of vectors of ints, initialized to contain 4 vectors that are initialized to contain 4 ints, initialized to 0. (You could specify a default value for the int to, if desired.)

A mouth-full, but not too hard. :)


For a pair:

typedef std::pair<int, int> pair_type; // be liberal in your use of typedef
typedef std::vector<pair_type> inner_vec;
typedef std::vector<inner_vec> outer_vec;

outer_vec v(5, inner_vec(5, pair_type(1, 1)); // 5x5 of pairs equal to (1, 1)
//             this many ^ of these ^
//this many ^      of these ^
like image 65
GManNickG Avatar answered Oct 06 '22 11:10

GManNickG


Alternatively to a std::vector you can use boost::multi_array. From the documentation:

#include "boost/multi_array.hpp"
#include <cassert>

int 
main () {
  // Create a 3D array that is 3 x 4 x 2
  typedef boost::multi_array<double, 3> array_type;
  typedef array_type::index index;
  array_type A(boost::extents[3][4][2]);

  // Assign values to the elements
  int values = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        A[i][j][k] = values++;

  // Verify values
  int verify = 0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
      for(index k = 0; k != 2; ++k)
        assert(A[i][j][k] == verify++);

  return 0;
}
like image 20
wilhelmtell Avatar answered Oct 06 '22 12:10

wilhelmtell