2d Vectors

Dear All. I'd appreciate some help. I want to be able to write functions that can handle both 1d and 2d vectors being passed to them. I also want to understand how vectors of vectors work. This is my first bash.

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
#include <iostream>
#include <vector>
#include <string>
using namespace std;

template <class arr> void print(arr v, int elmts, int nCols=0);

int main ()
{
  vector<vector<int> > v (5, vector<int> (2));
  v[0][0] = 99;
  v[1][0] = 10;
  v[0][1] = 1;
  v[1][1] = 11;
  print(&v[0][0], 10, 1);
  return 0;
}

template <class arr> void print(arr v, int elmts, int nCols)
{
  for (int i=0; i < elmts; i++)
  {
	cout << *(v+i) << ((!((i+1) & nCols)) ? "\n" : ", ");
  }
}


It's successful in a sense. But the output I get is

99, 1
0, 0
10, 11
0, 0
0, 0


which isn't what I expected. Can anyone explain things to me please?
Last edited on
Well, ... you just can't do that. Each vector in it has 3 pointers as data members. One of the
pointers is a pointer to the first allocated element. A two-dimensional "array" of vectors is
not wholly contiguous in memory. In your case, you have a vector (v) containing 5 vectors.
Each of those 5 vectors contains 2 integers. There are 6 non-contiguous blocks of memory
allocated:

1. v allocated memory large enough to store 5 vector instances.
2-6. Each of the 5 vectors allocated memory large enough to store 2 integers.

Thanks for the reply. I'm not sure I quite get you though. Let me see. Are you saying the 'first' vector contains a pointer to a bit of memory big enough to hold 5 pointers to other vectors, and that those 5 pointers then point to a 'second', 'third', ..., and 'sixth' vector, each of which contains a pointer to memory location holding 2 integers? If so, I think I understand what you're saying. In which case I'm better off using a 2d array for this kind of thing?
Here is a synopsis of vector:

1
2
3
4
5
6
template< typename Tp >
class vector {
    Tp* start;
    Tp* finish;
    Tp* capacity;
};


'v' is a vector which has 5 elements of type "vector<int>". In v, start points to a block of memory at least
large enough to store 5 vectors. As you can see, vector uses 12 bytes of memory for its data members
on a 32-bit machine. Therefore, the buffer will be at least 5 * 12 = 60 bytes wide. finish and capacity
are both pointers to various locations within that buffer (unimportant for this discussion).

Each of the 5 contained vectors does the same thing. They each allocate their own block of memory
and point their own "start" pointer to it.


I cannot say what is an appropriate data structure for your purpose. It depends on your needs. If you
absolutely must have all elements in contiguous memory, then a vector of vectors is not usable.
Otherwise, because vector manages the memory for you, I'd say it is a better choice.

Topic archived. No new replies allowed.