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 起) (C++23 起 constexpr) |
|
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 前) |
目录 |
[edit] 参数
零 | - | 用于表示 false 的字符 |
一 | - | 用于表示 true 的字符 |
[edit] 返回值
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)。
[edit] 异常
可能从 std::basic_string 构造函数抛出 std::bad_alloc。
[edit] 注意
自 C++11 起,函数模板可以有默认模板实参。LWG issue 1113 移除了辅助重载 (2-4) 并在 (1) 中添加了相应的默认模板实参。
[edit] 示例
运行此代码
#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
[edit] 缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 发布时的行为 | 正确的行为 |
---|---|---|---|
LWG 396 | C++98 | 零位和一位被转换为字符 0 和 1(不对应 '0' 和 '1') |
添加参数以提供 这些字符的值 |
LWG 434 | C++98 | 所有模板参数都需要提供 | 添加重载 (2-4) |
LWG 853 | C++98 | 重载 (2-4) 没有 LWG issue 396 添加的默认 参数 |
也添加了 |
[edit] 参见
返回数据的 unsigned long 整型表示 (公共成员函数) | |
(C++11) |
返回数据的 unsigned long long 整型表示 (公共成员函数) |