Двоичное число от 0 до n с одинаковыми номерами символов / - PullRequest
0 голосов
/ 06 мая 2018

Я хочу создать программу, которая будет представлять собой двоичные числа в двоичной базе от o до n, и я хочу, чтобы у всех было одинаковое число символов. Вот код:

#include <iostream>
#include <bitset>
#include <string>
#include <vector>
#include <cmath>
#include <stdio.h>
using namespace std;  
vector<string> temp;
int BinaryNumbers(int number)
    { 
        const int HowManyChars= ceil(log(number));
        for(int i = 0; i<number; i++)
        {
            bitset<HowManyChars> binary(i); 
            temp.push_back(binary.to_string());                             
        }
    }

int main(){
    BinaryNumbers(3);
    for(int i=0; i<temp.size();i++)
    {
        cout<<temp[i]<<endl;
    }
    return 0;
}

Моя проблема в том, что я не могу установить число битов <> (HowManyChars) "[Ошибка] 'HowManyChars' не может появляться в константном выражении"

Ответы [ 2 ]

0 голосов
/ 08 мая 2018

В C ++ 17 появилась новая функция to_chars.Одна из функций (1) берет базу в последнем параметре.

// use numeric_limits to find out the maximum number of digits a number can have
constexpr auto reserve_chars = std::numeric_limits< int >::digits10 + 1; // +1 for '\0' at end;

std::array< char, reserve_chars > buffer;

int required_size = 9; // this value is configurable

assert( required_size < reserve_chars ); // a check to verify the required size will fit in the buffer

// C++17 Structured bindings return value. convert value "42" to base 2.
auto [ ptr, err ] = std::to_chars( buffer.data(), buffer.data() + required_size, 42 , 2);

// check there is no error
if ( err == std::errc() )
{
    *ptr = '\0'; // add null character to end
    std::ostringstream str; // use ostringstream to create a string pre-filled with "0".
    str << std::setfill('0') << std::setw(required_size) << buffer.data();

    std::cout << str.str() << '\n';
}
0 голосов
/ 07 мая 2018

Возможное решение - использовать максимальный размер bitset для создания строки.Затем верните только последние символы из строки.

...