练习17.9
解释下列每个bitset对象所包含的位模式:
(a) bitset<64> bitvec(32);
(b) bitset<32> bv(1010101);
(c) string bstr; cin >> bstr; bitset<8> bv(bstr);
解答:
(a) 0x 0000 0000 0010 0000
(b) 0x 000F 69B5
(c) 这个取决于你的输入。
1010 输入
00001010 输出的位模式
0111010111 输入
01110101 输出的位模式
11001110 输入
11001110 输出的位模式
这个规律也很明显了,书642页上也有提示。
练习17.10
使用序列1、2、3、5、8、13、21初始化一个bitset,将这些位置置位。对另一个bitset进行默认初始化,并编写一小段程序将其恰当的位置位。
解答:
#include <iostream>
#include <bitset>
using namespace std;
int main(){
bitset<22> a("1000000010000100101110");
bitset<22> b;
b.set(1);
b.set(2);
b.set(3);
b.set(5);
b.set(8);
b.set(13);
b.set(21);
cout << a << endl;
cout << b << endl;
}
这里序列位从0算起的。
练习17.11
定义一个数据结构,包含一个整型对象,记录一个包含10个问题的真/假测试的解答。如果测试包含100道题,你需要对数据结构做出什么改变(如果需要的话)?
解答:
10个问题使用size_t就够用了。但是,当有100道题的时候,单个整数就够用了,因为2的100次方已经超过了任何内置类型的最大值,这里可能就要使用两个整型对象了,一个存储1到64题,另一个存储65到100题的结果。
<pre name="code" class="cpp">class result{
public:
size_t _1_64, _65_128;
};
如果不使用整型对象,这样的问题可以直接用数组来解决,例如:初始化一个answer[10]={0}; answer[100] = {0}。
不过这里可以使用bitset+模板来解决这个问题
<pre name="code" class="cpp">#include <iostream>
#include <bitset>
using namespace std;
template <unsigned int N>
bitset<N> initbit(){
bitset<N> init;
return init;
}
int main(){
auto bitset10 = initbit<10>();
auto bitset100 = initbit<100>();
cout << bitset10 << endl;
cout << bitset100 << endl;
}
这里用的是函数,也可以用类的方式来解决。
不过自定义类,没有直接使用bitset来得方便。
练习17.12
使用前一题中的数据结构,编写一个函数,它接受一个问题编号和一个表示真假解答的值,函数根据这两个参数更新测验的解答。
解答:
和下一题一起解答。
练习17.13
编写一个整型对象,包含真假测验的额正确答案。使用它来为前两题中的数据结构生成测验成绩。
解答:
#include <iostream>
#include <bitset>
using namespace std;
class result{
public:
result() = delete;
result(size_t a, size_t b) :_1_64(0), _65_128(0),a_1_64(a), a_65_128(b){}
void test_answer(size_t num, size_t answer){
if (num < 65){
_1_64 |= (!!answer) << (num - 1);
}
else{
_65_128 |= (!!answer) << (num - 1);
}
}
void checkout(){
_1_64 &= a_1_64;
_65_128 &= a_65_128;
bitset<64> low(_1_64), hight(_65_128);
cout << "the number of correct answer is " << (low.count() + hight.count()) << endl;
}
private:
size_t _1_64, _65_128;
size_t a_1_64, a_65_128;
};
int main(){
result res(12345, 78909);
res.test_answer(1, 1);
res.checkout();
}