### How to implement 3 digit binary numbers into 2D vector in C++?

I want to write a C++ code contain all 3bits binary numbers into a 2D vector like the following matrix:

0, 0, 0, 1, 1, 1, 1
0, 1, 1, 0, 0, 1, 1
1, 0, 1, 0, 1, 0, 1

Last edited on
? are your numbers stored vertically??

regardless, would
vector<vector<bool>> do it for you?

Have you edited it to miss the first column?

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243`` ``````#include #include #include using namespace std; #define BIT bool // Also: short or int using matrix = vector< vector >; //====================================================================== matrix populate( int N ) { int size = 1 << N; matrix M( N, vector( size ) ); for ( int j = 0; j < size; j++ ) { for ( int i = 0; i < N; i++ ) M[N-1-i][j] = bool( j & ( 1 << i ) ); // bool() necessary if BIT is int } return M; } //====================================================================== void print( const matrix &M ) { string SPACER = ", "; int cols = M[0].size(); for ( auto R : M ) { for ( int j = 0; j < cols - 1; j++ ) cout << R[j] << SPACER; cout << R[cols-1] << '\n'; } } //====================================================================== int main() { const int N = 3; matrix M = populate( N ); print( M ); }``````

 ```0, 0, 0, 0, 1, 1, 1, 1 0, 0, 1, 1, 0, 0, 1, 1 0, 1, 0, 1, 0, 1, 0, 1```
Last edited on
I need this 3digits binary matrix by using vector of vector in C++ like: vector<vector<int>>
and also the result matrix must be stored vertically like:

0, 0, 0, 1, 1, 1, 1
0, 1, 1, 0, 0, 1, 1
1, 0, 1, 0, 1, 0, 1

Last edited on
Well, you will have a vector< vector<int> > if you change line 6 of my code to
`#define BIT int `
(I deliberately left the storage type easy to change).

The matrix is set up for 23 = 8 columns, but if you wish to omit the first column of all zeros when writing it out then simply change the lower limit of the loop in line 31 from 0 to 1:
` for ( int j = 1; j < cols - 1; j++ ) cout << R[j] << SPACER;`
I don't see any purpose to reducing the actual size in store of M, but should you wish to then you will have to amend function populate to your needs.

If you prefer, there are other, more obvious, ways of finding the binary digits of a number than the bit-shifting which I did on line 17. Just playing here.

The code is broken up in this way because:
- I like main() to be simple, often just directing the calls to tasks done by other functions;
- I prefer functions to be short and do just one thing;
- I like functions that are, to some degree, reusable.

Last edited on
Topic archived. No new replies allowed.