bitset
Bitset
A bitset stores bits (elements with only two possible values: 0 or 1, true
or false
, ...).
(1)构造函数
#include <iostream> // std::cout
#include <string> // std::string
#include <bitset> // std::bitset
using namespace std;
int main ()
{
bitset<16> foo;
bitset<16> bar (0xfa2);
bitset<16> baz (string("0101111001"));
cout << "foo: " << foo << '\n';
cout << "bar: " << bar << '\n';
cout << "baz: " << baz << '\n';
return 0;
}
输出
foo: 0000000000000000
bar: 0000111110100010
baz: 0000000101111001
(2)count()
// bitset::count
#include <iostream> // cout
#include <string> // string
#include <bitset> // bitset
using namespace std;
int main ()
{
bitset<8> foo (string("10110011"));
cout << foo << " has ";
cout << foo.count() << " ones and ";
cout << (foo.size()-foo.count()) << " zeros.\n";
return 0;
}
输出
10110011 has 5 ones and 3 zeros
(3)size()
#include <iostream> // cout
#include <string> // string
#include <bitset> // bitset
using namespace std;
int main ()
{
bitset<8> foo;
bitset<4> bar;
cout << "foo.size() is " << foo.size() << '\n';
cout << "bar.size() is " << bar.size() << '\n';
return 0;
}
输出
foo.size() is 8
bar.size() is 4
(4)test
using namespace std;
#include <iostream> // cout
#include <string> // string
#include <cstddef> // size_t
#include <bitset> // bitset
int main ()
{
bitset<5> foo (string("01011"));
cout << "foo contains:\n";
for (size_t i=0; i<foo.size(); ++i)
cout << foo.test(i) <<" ";
cout << boolalpha<<endl;
for (size_t i=0; i<foo.size(); ++i)
cout << foo.test(i) <<" ";
return 0;
}
结果
foo contains:
1 1 0 1 0
true true false true false
(5)any
using namespace std;
#include <iostream> // cout
#include <string> // string
#include <cstddef> // size_t
#include <bitset> // bitset
int main ()
{
bitset<16> foo;
cout << "Please, enter a binary number: ";
cin >> foo;
if (foo.any())
cout << foo << " has " << foo.count() << " bits set.\n";
else
cout << foo << " has no bits set.\n";
return 0;
}
输出
Please, enter a binary number: 10110
0000000000010110 has 3 bits set.
(6)none
// bitset::none
#include <iostream> // cin, cout
#include <bitset> // bitset
using namespace std;
int main ()
{
bitset<16> foo;
cout << "Please, enter a binary number: ";
cin >> foo;
if (foo.none())
cout << foo << " has no bits set.\n";
else
cout << foo << " has " << foo.count() << " bits set.\n";
return 0;
}
输出
Please, enter a binary number: 11010111
0000000011010111 has 6 bits set.
(7)all
// bitset::all
#include <iostream> // cin, cout
#include <bitset> // bitset
using namespace std;
int main ()
{
bitset<8> foo;
cout << "Please, enter an 8-bit binary number: ";
cin >> foo;
cout << boolalpha;
cout << "all: " << foo.all() << '\n';
cout << "any: " << foo.any() << '\n';
cout << "none: " << foo.none() << '\n';
return 0;
}
输出
Please, enter an 8-bit binary number: 11111111
all: true
any: true
none: false
因上求缘,果上努力~~~~ 作者:图神经网络,转载请注明原文链接:https://www.cnblogs.com/BlairGrowing/p/13553233.html