C++位集有趣的事实

位集 是C++标准模板库中的一个容器,用于处理位级别的数据。

null

1.位集存储位(只有两个可能值的元素:0或1)。但是,我们可以通过向位集构造函数提供位置来获得字符串的部分(位置是相对于从左到右的字符串位置)

例子:

C++

// C++ program to demonstrate that we can get part of a
// bit string in bitset.
#include <bitset>
#include <string>
#include <iostream>
int main()
{
std::string bit_string = "110010" ;
std::bitset<8> b1(bit_string); // [0, 0, 1, 1, 0, 0, 1, 0]
// string from position 2 till end
std::bitset<8> b2(bit_string, 2); // [0, 0, 0, 0, 0, 0, 1, 0]
// string from position 2 till next 3 positions
std::bitset<8> b3(bit_string, 2, 3); // [0, 0, 0, 0, 0, 0, 0, 1]
std::cout << b1 << '' << b2 << '' << b3 << '' ;
return 0;
}


输出:

001100100000001000000001

2.我们可以使用std::basic_string_str中的字符构造位集。可以提供可选的起始位置和长度,以及表示set(_one)和unset(_zero)位的替代值的字符。

语法:

std::bitset b1(str, pos, n, zero, one);str    : string used to initialize the bitsetpos    : a starting offset into strn    : number of characters to use from strzero    : alternate character for unset bits in strone    : alternate characters for set bits in str 
  • 如果_pos>str.size(),此构造函数将std::抛出_范围之外。
  • 如果在_str中检查的任何字符不是零或一,它将抛出std::invalid_参数。

C++

// C++ program to demonstrate that we can construct bitset using
// alternate characters for set and unset bits.
#include <bitset>
#include <string>
#include <iostream>
int main()
{
// string constructor using custom zero/one digits
std::string alpha_bit_string = "aBaaBBaB" ;
std::bitset<8> b1(alpha_bit_string, 0, alpha_bit_string.size(),
'a' , 'B' ); // [0,1,0,0,1,1,0,1]
std::cout << b1 << '' ;
}


输出:

01001101

3.构造bitset类的对象,将N位初始化为与c样式的0和1字符串中提供的字符相对应的值。调用构造函数时,不会将字符串转换为字符串类型。它还有两个可选参数,_Zero和_One,分别表示_Str中的哪个字符将被解释为0位和1位。

C++

#include <bitset>
#include <iostream>
int main()
{
// char* constructor using custom digits
std::bitset<8> b1( "XXXXYYYY" , 8, 'X' , 'Y' ); // [0, 0, 0, 0, 1, 1, 1, 1]
std::cout << b1 << '' ;
}


输出:

00001111

位集运算

1.std::bitset::to_string() 将位集的内容转换为字符串。使用0表示值为false的位,使用1表示值为true的位。结果字符串包含N个字符,第一个字符对应于最后一位(N-1),最后一个字符对应于第一位。此外,我们还可以通过参数传递用于打印真值和假值的字符。

例子:

C++

// C++ program to demonstrate that we can convert contents
// of bitset to a string.
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b(42);
std::cout << b.to_string() << ''
<< b.to_string( '*' ) << ''
<< b.to_string( 'O' , 'X' ) << '' ;
}


输出:

00101010**1*1*1*OOXOXOXO

2.std::bitset::to_ulong(): 将位集的内容转换为无符号长整数。位集的第一位对应于数字的最低有效位,最后一位对应于最高有效位。如果值不能用无符号long表示,函数将抛出std::overflow_错误。

例子:

C++

// C++ program to demonstrate that we can get value of bitset
// as  unsigned long integer.
#include <iostream>
#include <bitset>
int main()
{
std::bitset<5> b(5);
std::cout << b.to_ulong() << '' ;
}


输出:

5
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享