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
in fact, i need 2d vector contains 3 digits binary numbers, verticlly
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.
In function 'constexpr long long unsigned int ubound(std::size_t)':
line 13:1: error: a function-definition is not allowed here before '{' token
line 49:1: error: expected '}' at end of input
line 49:1: error: body of constexpr function 'constexpr long long unsigned int ubound(std::size_t)' not a return-statement
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.
Registered users can post here. Sign in or register to post.