Monday 20 July 2009

Simple example of BitSets in C++

From "The C++ Standard Library" By Nicolai M Josuttis: A bitset is a bitfield with an arbitrary but fixed number of bits. You can consider it a container for bits or Boolean values. Note that the C++ standard library also provides a special container with a variable size for Boolean values: vector.

Lets write a simple program using rainbow colours.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of BitSets
#include<iostream>
#include<bitset>

using namespace
std;

int
main()
{

enum
Colour {red, orange, yellow, green, blue, indigo, violet, numOfColours};

bitset<numOfColours> usedColours;

usedColours.set(red);
usedColours.set(blue);

//Lets see the output
cout << "bitfield of used colours: " << usedColours << endl;
cout << "number of used colors: " << usedColours.count() << endl;
cout << "bitfield of unused colors: " << ~usedColours << endl;

//If any colour is used
if (usedColours.any())
{

// loop over all colors
for (int c = 0; c < numOfColours; ++c)
if
(usedColours[(Colour)c])
cout << Colour(c)<< " used "<<endl; //No way to print enum names directly
}

return
0;
}

The output is as follows:


Reference:


No comments:

Post a Comment