|
Boost : |
From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2001-05-11 07:07:14
Beman Dawes wrote:
> Good question. I don't know the answer. Does anyone have real-world
> examples (NOT GUESSES!) as to how people are using vector<bool>?
Below is one of such, almost unvarnished :). The code is pretty clean, so I
won't go into much explanation.. more examples to come, though :)
#include <vector>
#include <iostream>
//------------------------ real-world part
----------------------------------
// 'counters_pool' class keeps track of used numbers in interval
// [0..max_requested_so_far]; every next value requested from pool
// will be the least unused number in the interval
struct counters_pool
{
typedef std::vector<bool> values_pool;
typedef values_pool::size_type value_type;
value_type next_value()
{
values_pool::iterator i = std::find(pool_.begin(), pool_.end(),
false);
if (i != pool_.end())
{
*i = true;
return i - pool_.begin();
}
pool_.push_back(true);
return pool_.size() - 1;
}
void put_back( value_type v ) { pool_[v] = false; }
private:
values_pool pool_;
};
// per-class "smart" objects counter
template<class T>
struct smart_counter
{
typedef counters_pool::value_type value_type;
smart_counter() : value_( pool_.next_value() ) {}
~smart_counter() { pool_.put_back( value_ ); }
value_type value() const { return value_; }
operator value_type() const { return value(); }
private:
static counters_pool pool_;
const value_type value_;
};
template<class T>
counters_pool smart_counter<T>::pool_;
//------------------- my usage example
--------------------------------------
struct window
{
smart_counter<window> counter;
};
// program output:
// 0121
int main()
{
window m0;
std::cout << m0.counter;
if (true)
{
window m1;
std::cout << m1.counter;
window m2;
std::cout << m2.counter;
}
window m3;
std::cout << m3.counter;
return 0;
}
Aleksey
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk