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

Mar 2, 2018 at 11:09am
.
Last edited on Apr 25, 2018 at 5:16pm
Mar 2, 2018 at 11:17am
You already have a thread on this, with some answers: http://www.cplusplus.com/forum/general/229485/
Mar 2, 2018 at 11:51am
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
Mar 2, 2018 at 12:04pm
there are some errors in this code, unfortunately
Mar 2, 2018 at 1:26pm
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.
Mar 2, 2018 at 1:56pm
.
Last edited on Apr 25, 2018 at 5:15pm
Mar 2, 2018 at 2:00pm
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
Mar 2, 2018 at 2:24pm
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.