0

Hey I was curious about creating a 2 dimensional vector of chars so I know it's a vector inside a vector and I'd like to initialize all values to ','.

So i know this much I believe

vector<vector<char>> spaceStation();

I'm guessing the columns and rows go in the parenthesis but I'm not exactly sure.

Thanks!

user2817753
  • 1
  • 1
  • 1
  • 2
  • 3
    First, replace `>>` with `> >` with spaces in between. – Yu Hao Sep 26 '13 at 03:09
  • [std::vector](http://en.cppreference.com/w/cpp/container/vector) You can go here to check the constructor arguments. –  Sep 26 '13 at 03:09
  • May be a help: http://stackoverflow.com/questions/2236197/c-easiest-way-to-initialize-an-stl-vector-with-hardcoded-elements – diegoperini Sep 26 '13 at 03:10
  • This question comes up about once a week on here. Look around and do some digging. Ask yourself, do you want all the 'sub-vectors' to be of the same length, ie matrix? Or do you want them all the same, ie a vector of vectors? If the second, you're on the right track, if the fisrt I suggest you flat pack it. – Cramer Sep 26 '13 at 03:14
  • 1
    `vector> spaceStation(5, vector(10, ','));` will create 5x10 matrix, all containing `','`. – Cornstalks Sep 26 '13 at 03:14
  • 2
    @YuHao: If using C++11, that no longer is necessary. – Cornstalks Sep 26 '13 at 03:14

1 Answers1

1

If it is going to be a nxn or nxm 2D matrix that you are looking for, where n and m can be determined before the creation of the matrix (even if it at run time) then vector of vectors may not be the most efficient way to go about it. Internally the way vector grows is by allocating a bigger memory if the current allocated space gets filled up and moving all the existing data to the new location. Similarly inserting a new first row would require all the vectors to move down which would in turn result in copying all the other vectors and its elements down.

If you know n,m, even if it is at run time you could allocated a big block of memory using a single vector (of size n^2 or nxm) and access elements logically as a vector (a[i][j] would be vector[i*n + j]) thus efficiently managing a single memory block.

jayadev
  • 3,576
  • 25
  • 13