#include <iostream>
#include <vector>
#include <string>
usingnamespace std;
#define BIT bool // Also: short or int
using matrix = vector< vector<BIT> >;
//======================================================================
matrix populate( int N )
{
int size = 1 << N;
matrix M( N, vector<BIT>( 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()
{
constint N = 3;
matrix M = populate( N );
print( M );
}
Thanks for your answers
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:
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.