Я хочу сделать программу, которая будет генерировать числа в двоичной базе от 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' не может отображаться в константном выражении»





Возможное решение - использовать bitset максимального размера для создания строки. Затем верните только последние символы подсчета из строки.
В 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';
}
Возможный дубликат Определить размер битового набора при инициализации?