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

.
Last edited on
You already have a thread on this, with some answers: http://www.cplusplus.com/forum/general/229485/
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <limits>
#include <vector>
#include <algorithm>

constexpr unsigned long long ubound( std::size_t nbits )
{
    if( nbits < 2 ) return 2 ;
    else return ubound( nbits-1 ) * 2 ;
}

std::vector< std::vector<int> > generate_mtx( std::size_t nbits )
{
    nbits %= std::numeric_limits<unsigned long long>::digits ;

    std::vector< std::vector<int> > result(nbits) ;

    // note: col with all zeroes is skipped (start with number = 0 to include it)
    for( unsigned long long number = 1 ; number < ubound(nbits) ; ++number )
    {
        auto n = number ;
        for( auto& vec : result )
        {
            vec.push_back( n%2 ) ;
            n /= 2 ;
        }
    }
    
    // to get the rows in the same order as illustrated in the example  
    std::reverse( std::begin(result), std::end(result) ) ;
    
    return result ;
}

int main()
{
    for( std::size_t nbits = 2 ; nbits < 7 ; ++nbits )
    {
        std::cout << "nbits == " << nbits << '\n' ;
        
        for( const auto& row : generate_mtx(nbits) )
        {
            for( int v : row ) std::cout << v << ' ' ;
            std::cout << '\n' ;
        }

        std::cout << "\n-------------\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/de9bc4d5cc69d2c0
there are some errors in this code, unfortunately
There is no such thing as "some errors" in programming. If there is an error, then there must be an exact description of the error too. The details are vital, when solving problems.
.
Last edited on
The code requires C++14.

For C++11, rewrite the function as:
1
2
constexpr unsigned long long ubound( std::size_t nbits )
{ return nbits < 2 ? 2 : ubound( nbits-1 ) * 2 ; }

http://coliru.stacked-crooked.com/a/8181420c91bc70b5
It seems that the cpp.sh's compiler (presumably GCC), even when it is in c++14 mode, returns the
body of constexpr function ‘...’ not a return-statement

(GCC) 5.3.1 20160406 (Red Hat 5.3.1-6) does not have that issue.

The cpp.sh's compiler is probably a bit older version, with incomplete C++14 support.
Topic archived. No new replies allowed.