std::bitset<N>::to_string
来自 cppreference.cn
(1) | ||
template< class CharT, class Traits, class Allocator > std::basic_string<CharT, Traits, Allocator> |
(直到 C++11) | |
template< class CharT = char, |
(自 C++11 起) (constexpr 自 C++23 起) |
|
template< class CharT, class Traits > std::basic_string<CharT, Traits> |
(2) | (直到 C++11) |
template< class CharT > std::basic_string<CharT> to_string( CharT zero = CharT('0'), |
(3) | (直到 C++11) |
std::string to_string( char zero = '0', char one = '1' ) const; |
(4) | (直到 C++11) |
将 bitset 的内容转换为字符串。使用 zero 表示值为 false 的位,使用 one 表示值为 true 的位。
结果字符串包含 N 个字符,第一个字符对应于最后一位(第 N-1th 位),最后一个字符对应于第一位。
所有模板类型参数都需要提供,因为函数模板不能有默认模板参数。提供了重载 (2-4) 以简化 2) 使用默认分配器 std::allocator。
|
(直到 C++11) |
目录 |
[编辑] 参数
zero | - | 用于表示 false 的字符 |
one | - | 用于表示 true 的字符 |
[编辑] 返回值
1) 转换后的字符串。
2) to_string<CharT, Traits, std::allocator<CharT>>(zero, one)。
3) to_string<CharT, std::char_traits<CharT>, std::allocator<CharT>>(zero, one)。
4) to_string<char, std::char_traits<char>, std::allocator<char>>(zero, one)。
[编辑] 异常
可能从 std::basic_string 构造函数抛出 std::bad_alloc。
[编辑] 注意
自 C++11 起,函数模板可以具有默认模板参数。LWG issue 1113 移除辅助重载 (2-4) 并在 (1) 中添加了相应的默认模板参数。
[编辑] 示例
运行此代码
#include <bitset> #include <iostream> int main() { std::bitset<8> b{42}; std::cout << b.to_string() << '\n' << b.to_string('*') << '\n' << b.to_string('O', 'X') << '\n'; }
输出
00101010 **1*1*1* OOXOXOXO
[编辑] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 396 | C++98 | 零和一位被转换为字符 0 和 1 (这与 '0' 和 '1' 不对应) |
添加参数以提供 这些字符的值 |
LWG 434 | C++98 | 需要提供所有模板参数 | 添加了重载 (2-4) |
LWG 853 | C++98 | 重载 (2-4) 没有 LWG issue 396 添加的默认参数 arguments added by LWG issue 396 |
也添加了 |
[编辑] 参见
返回数据的 unsigned long 整数表示形式 (公共成员函数) | |
(C++11) |
返回数据的 unsigned long long 整数表示形式 (公共成员函数) |