从 0 到 n 的二进制数,具有相同数量的字符/

Binary number from 0 to n having the same numbers of chars/

本文关键字:字符 二进制数      更新时间:2023-10-16

我想使proggram wchich将是二进制基数从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 '' 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 = ''; // 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';
}