
dynamic_bitset<Block, Allocator>
Contents
- Description
- Synopsis
- Definitions
- Examples
- Rationale
- Header Files
- Template Parameters
- Concepts modeled
- Type requirements
- Public base classes
- Nested type names
- Public data members
- Constructors
- Destructor
- Member functions
- Non-member functions
- Exception guarantees
- Changes from previous version(s)
- See also
- Acknowledgements
Description
Dynamic_bitsetКласс представляет собой набор битов. Он обеспечивает доступ к значению отдельных битов через оператор.и предоставляет все битовые операторы, которые можно применить к встроенным целым числам, таким какоператор &иоператор<<. Количество битов в наборе указывается во время выполнения через параметр конструкторуdynamic_bitset..
Классdynamic_bitsetпочти идентичен классуstd::bitset. Разница заключается в том, что размердинамического_битсета(число бит) указывается во время выполнения во время построениядинамического_битсетаобъекта, тогда как размерstd::bitsetуказывается во время компиляции через целочисленный параметр шаблона.
Основная задача, для решения которой предназначендинамический_битсет, заключается в представлении подмножества конечного множества. Каждый бит представляет, находится ли элемент конечного множества в подмножестве или нет. Как таковые битовые операцииdynamic_bitset, такие какoperator&иoperator |, соответствуют заданным операциям, таким как пересечение и объединение.
Synopsis
namespace boost { template <typename Block, typename Allocator> class dynamic_bitset { public: typedef Block block_type; typedef Allocator allocator_type; typedef implementation-defined size_type; static const int bits_per_block = implementation-defined; static const size_type npos = implementation-defined; class reference { void operator&(); // not defined public: // An automatically generated copy constructor. reference& operator=(bool value); reference& operator=(const reference& rhs); reference& operator|=(bool value); reference& operator&=(bool value); reference& operator^=(bool value); reference& operator-=(bool value); bool operator~() const; operator bool() const; reference& flip(); }; typedef bool const_reference; explicit dynamic_bitset(const Allocator& alloc = Allocator()); explicit dynamic_bitset(size_type num_bits, unsigned long value = 0, const Allocator& alloc = Allocator()); template <typename CharT, typename Traits, typename Alloc> explicit dynamic_bitset(const std::basic_string<CharT, Traits, Alloc>& s, typename std::basic_string<CharT, Traits, Alloc>::size_type pos = 0, typename std::basic_string<CharT, Traits, Alloc>::size_type n = std::basic_string<CharT, Traits, Alloc>::npos, const Allocator& alloc = Allocator()); template <typename BlockInputIterator> dynamic_bitset(BlockInputIterator first, BlockInputIterator last, const Allocator& alloc = Allocator()); dynamic_bitset(const dynamic_bitset& b); dynamic_bitset(dynamic_bitset&& b); void swap(dynamic_bitset& b); dynamic_bitset& operator=(const dynamic_bitset& b); dynamic_bitset& operator=(dynamic_bitset&& b); allocator_type get_allocator() const; void resize(size_type num_bits, bool value = false); void clear(); void pop_back(); void push_back(bool bit); void append(Block block); template <typename BlockInputIterator> void append(BlockInputIterator first, BlockInputIterator last); dynamic_bitset& operator&=(const dynamic_bitset& b); dynamic_bitset& operator|=(const dynamic_bitset& b); dynamic_bitset& operator^=(const dynamic_bitset& b); dynamic_bitset& operator-=(const dynamic_bitset& b); dynamic_bitset& operator<<=(size_type n); dynamic_bitset& operator>>=(size_type n); dynamic_bitset operator<<(size_type n) const; dynamic_bitset operator>>(size_type n) const; dynamic_bitset& set(size_type n, bool val = true); dynamic_bitset& set(); dynamic_bitset& reset(size_type n); dynamic_bitset& reset(); dynamic_bitset& flip(size_type n); dynamic_bitset& flip(); bool test(size_type n) const; bool test_set(size_type n, bool val = true); bool all() const; bool any() const; bool none() const; dynamic_bitset operator~() const; size_type count() const noexcept; reference operator[](size_type pos); bool operator[](size_type pos) const; unsigned long to_ulong() const; size_type size() const noexcept; size_type num_blocks() const noexcept; size_type max_size() const noexcept; bool empty() const noexcept; size_type capacity() const noexcept; void reserve(size_type num_bits); void shrink_to_fit(); bool is_subset_of(const dynamic_bitset& a) const; bool is_proper_subset_of(const dynamic_bitset& a) const; bool intersects(const dynamic_bitset& a) const; size_type find_first() const; size_type find_next(size_type pos) const; }; template <typename B, typename A> bool operator==(const dynamic_bitset<B, A>& a, const dynamic_bitset<B, A>& b); template <typename Block, typename Allocator> bool operator!=(const dynamic_bitset<Block, Allocator>& a, const dynamic_bitset<Block, Allocator>& b); template <typename B, typename A> bool operator<(const dynamic_bitset<B, A>& a, const dynamic_bitset<B, A>& b); template <typename Block, typename Allocator> bool operator<=(const dynamic_bitset<Block, Allocator>& a, const dynamic_bitset<Block, Allocator>& b); template <typename Block, typename Allocator> bool operator>(const dynamic_bitset<Block, Allocator>& a, const dynamic_bitset<Block, Allocator>& b); template <typename Block, typename Allocator> bool operator>=(const dynamic_bitset<Block, Allocator>& a, const dynamic_bitset<Block, Allocator>& b); template <typename Block, typename Allocator> dynamic_bitset<Block, Allocator> operator&(const dynamic_bitset<Block, Allocator>& b1, const dynamic_bitset<Block, Allocator>& b2); template <typename Block, typename Allocator> dynamic_bitset<Block, Allocator> operator|(const dynamic_bitset<Block, Allocator>& b1, const dynamic_bitset<Block, Allocator>& b2); template <typename Block, typename Allocator> dynamic_bitset<Block, Allocator> operator^(const dynamic_bitset<Block, Allocator>& b1, const dynamic_bitset<Block, Allocator>& b2); template <typename Block, typename Allocator> dynamic_bitset<Block, Allocator> operator-(const dynamic_bitset<Block, Allocator>& b1, const dynamic_bitset<Block, Allocator>& b2); template <typename Block, typename Allocator, typename CharT, typename Alloc> void to_string(const dynamic_bitset<Block, Allocator>& b, std::basic_string<CharT, Alloc>& s); template <typename Block, typename Allocator, typename BlockOutputIterator> void to_block_range(const dynamic_bitset<Block, Allocator>& b, BlockOutputIterator result); template <typename CharT, typename Traits, typename Block, typename Allocator> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const dynamic_bitset<Block, Allocator>& b); template <typename CharT, typename Traits, typename Block, typename Allocator> std::basic_istream<CharT, Traits>& operator>>(std::basic_istream<CharT, Traits>& is, dynamic_bitset<Block, Allocator>& b); } // namespace boost
Definitions
Каждый бит представляет либо истинное, либо ложное значение (1 или 0). Длянаборнемного, чтобы назначить его 1. Дляясноилисброснемного, чтобы назначить его 0. Чтобыперевернутьбит, нужно изменить значение на 1, если оно было 0, и на 0, если оно было 1. Каждый бит имеет неотрицательноеположение. Битсетxсодержитx.size()биты, причем каждому биту присваивается уникальное положение в диапазоне[0,x.size()]. Бит в позиции 0 называетсянаименее значительным битом, а бит в позицииразмером () - 1являетсянаиболее значительным битом. При преобразовании экземпляраdynamic_bitsetв или из неподписанного длинногоn, бит в положенииiбитсета имеет то же значение, что и(n >>i) & 1.
Examples
Пример 1(настройка и чтение некоторых битов)
Пример 2(создание некоторых битсетов из целых чисел)
Пример 3(выполнение ввода/вывода и некоторых битовых операций).
Rationale
Dynamic_bitsetне является. Контейнери итераторы не предоставляются по следующей причине:
- Контейнер со ссылкой на проксине может выполнять требования к контейнеру, как указано в стандарте C++ (если не прибегнуть к странной семантике итератора).std::vector
имеет опорныйопорныйтип и не соответствует требованиям контейнера и в результате вызвал много проблем. Одна из распространенных проблем заключается в том, что люди пытаются использовать итераторы изstd::vector со стандартным алгоритмомstd::searchТребованияstd::searchговорят, что итератор должен бытьForward Iterator, ноstd::vector :::iterator не соответствует этому требованию из-за ссылки на прокси. В зависимости от реализации, они могут быть или не быть ошибкой компиляции или даже ошибкой времени выполнения из-за этого неправильного использования. Для дальнейшего обсуждения проблемы см.Effective STLСкотта Мейерса. Такdynamic_bitsetпытается избежать этих проблем, не притворяясь контейнером.
Некоторые люди предпочитают название «toggle» вместо «flip». Название «flip» было выбрано потому, что это имя используется вstd::bitset. По этой причине было выбрано большинство названий функций дляdynamic_bitset.
dynamic_bitsetне делает исключений при нарушении предварительного условия (как это делается вstd::bitset). Вместо этогоутверждается. См. руководство поОшибка и обработка исключенийдля объяснения.
Header Files
Классdynamic_bitsetопределен в заголовкеboost/dynamic_bitset.hpp. Кроме того, имеется форвардная декларация дляdynamic_bitsetв заголовкеboost/dynamic_bitset_fwd.hpp.
Template parameters
Parameter | Description | Default |
---|---|---|
Блок | Целый тип, в котором хранятся биты. | без подписи |
Распределитель | Тип распределителя, используемый для управления всей внутренней памятью. | std::allocator |
Concepts Modeled
Assignable, Default Constructible, Equality Comparable, LessThan Comparable.Type requirements
Block is an unsigned integer type. Allocator satisfies the Standard requirements for an allocator.Public base classes
None.Nested type names
dynamic_bitset::reference
Класс прокси, который действует как ссылка на один бит. Он содержит оператор назначения, преобразование вbool, оператор~и функцию членаflip. Он существует только как класс помощника для операторадинамического битсета. В следующей таблице описаны действительные операции поэталонномутипу. Предположим, чтоbявляется экземпляромдинамического_битсета,i, jимеютразмер_типи находятся в диапазоне[0,b.size()). Также обратите внимание, что когда мы пишемb[i], мы имеем в виду объект типассылки, который был инициализирован изb[i]. Переменнаяxпредставляет собойbool.
Expression | Semantics |
---|---|
x = b[i] | Назначьте битbнаx. |
(bool)b[i] | Возвращайте хеш битб. |
b[i] = x | Установите битbна значениеxи вернитеb [i]. |
b[i] |= x | Илиbс значениемxи возвратомb [i]. |
b[i] &= x | И хеш битbсо значениемxи возвратомb [i]. |
b[i] ^= x | Исключительно — или хеш-битbсо значениемxи возвратомb[i]. |
b[i] — = x | Еслиx==true, очистите битb. Возвращаетсяб[i]. |
b[i] = b[j] | Установите битbна значение j-битаbи вернитеb [i]. |
b[i] |= b[j] | Илибс j-битомби возвратомб [i]. |
b[i] &= b[j] | Ибс jth битби возвратб [i]. |
b[i] ^= b[j] | Исключительно — или хеш-битbс j-битомbи возвратомb [i]. |
b[i] — = b[j] | Еслиbзадан j-бит, очистите битb. Возвращаетсяб[i]. |
x = ~ b[i] | Назначьте противоположность бита ithbx. |
(bool)~b[i] | Возвращать противоположный хеш битб. |
b[i].flip() | Переверните битbи вернитеb [i]. |
dynamic_bitset::const_referenceThe type bool.
dynamic_bitset::size_typeThe unsigned integer type for representing the size of the bit set.
dynamic_bitset::block_typeThe same type as Block.
dynamic_bitset::allocator_type;The same type as Allocator.
Public data members
dynamic_bitset::bits_per_blockThe number of bits the type Block uses to represent values, excluding any padding bits. Numerically equal to std::numeric_limits<Block>::digits.
dynamic_bitset::nposThe maximum value of size_type.
Constructors
dynamic_bitset(const Allocator& alloc = Allocator())Effects: Constructs a bitset of size zero. A copy of the alloc object will be used in subsequent bitset operations such as resize to allocate memory.
Postconditions: this->size() == 0.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
(Required by Default Constructible.)
dynamic_bitset(size_type num_bits, unsigned long value = 0, const Allocator& alloc = Allocator())Effects: Constructs a bitset from an integer. The first M bits are initialized to the corresponding bits in value and all other bits, if any, to zero (where M = min(num_bits, std::numeric_limits<unsigned long>::digits)). A copy of the alloc object will be used in subsequent bitset operations such as resize to allocate memory. Note that, e.g., the following
dynamic_bitset b<>( 16, 7 );
will match the constructor from an iterator range (not this one), but the underlying implementation will still "do the right thing" and construct a bitset of 16 bits, from the value 7.
Postconditions:
- this->size() == num_bits
- Для всехiв диапазоне[0,M],(*это) [i] == (value >>i) & 1.
- Для всехiв диапазоне[M,num_bits],(*это) [i] == ложно.
dynamic_bitset(const dynamic_bitset& x)Effects: Constructs a bitset that is a copy of the bitset x. The allocator for this bitset is a copy of the allocator in x.
Postconditions: For all i in the range [0,x.size()), (*this)[i] == x[i].
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
(Required by Assignable.)
dynamic_bitset(dynamic_bitset&& x)Effects: Constructs a bitset that is the same as the bitset x, while using the resources from x. The allocator for this bitset is moved from the allocator in x.
Postconditions: For all i in the range [0,x.size()), (*this)[i] == x[i].
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
template <typename BlockInputIterator> explicit dynamic_bitset(BlockInputIterator first, BlockInputIterator last, const Allocator& alloc = Allocator());Effects:
- Если этот конструктор называется типомBlockInputIterator, которыйна самом деле является интегральным типом, библиотека ведет себя так, как если бы конструктор изнеподписанного длинногобыл вызван, с аргументамиstatic_cast
(первый), последний и выделенный , в этом порядке.
Пример:// b is constructed as if by calling the constructor // // dynamic_bitset(size_type num_bits, // unsigned long value = 0, // const Allocator& alloc = Allocator()) // // with arguments // // static_cast<dynamic_bitset<unsigned short>::size_type>(8), // 7, // Allocator() // dynamic_bitset<unsigned short> b(8, 7);
Примечание:
На момент написания этой статьи (октябрь 2008 г.) она была приведена в соответствие с предложенной резолюцией побиблиотечному номеру 438. Это изменениепостC++03и в настоящее время находится в рабочем документе дляC++0x. Неформально говоря, критические изменения в отношенииC++03являются падениемstatic_castна второй аргумент, и больше свободы действий в отношении, когдашаблонный конструктор должен иметь тот же эффект, что и (размер, значение) один: только когдаInputIteratorявляется интегральным типом, вC++03; когда это либо интегральный тип или любой другой тип, что реализация может обнаружить как невозможно быть итератором ввода, с предлагаемым разрешением. Для целейDynamic_bitsetмы ограничиваемся первым из этих двух изменений. - В противном случае, т.е., если аргумент шаблона не является интегральным типом, строит — при условии, что втребуетсяпункт — битсет на основе ряда блоков. Пусть*первымбудет блок No 0,*++ первымблоком No 1, и т.д. Блоковое числоbиспользуется для инициализации битов динамического_битсета в диапазоне положений[b*bits_per_block, (b+1)*bits_per_block). Для каждого числа блоковbсо значениемbval, бит(bval >>i) & 1соответствует биту в положении(b * bits_per_block + i)в битсете (гдеiпроходит через диапазон[0, bits_per_block)).
Requires: BlockInputIterator must be either an integral type or a model of Input Iterator whose value_type is the same type as Block.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
template<typename Char, typename Traits, typename Alloc> explicit dynamic_bitset(const std::basic_string<Char,Traits,Alloc>& s, typename std::basic_string<CharT, Traits, Alloc>::size_type pos = 0, typename std::basic_string<CharT, Traits, Alloc>::size_type n = std::basic_string<Char,Traits,Alloc>::npos, const Allocator& alloc = Allocator())Precondition: pos <= s.size() and the characters used to initialize the bits must be 0 or 1.
Effects: Constructs a bitset from a string of 0's and 1's. The first M bits are initialized to the corresponding characters in s, where M = min(s.size() - pos, n). Note that the highest character position in s, not the lowest, corresponds to the least significant bit. That is, character position pos + M - 1 - i corresponds to bit i. So, for example, dynamic_bitset(string("1101")) is the same as dynamic_bitset(13ul).
Throws: an allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
Destructor
~dynamic_bitset()Effects: Releases the memory associated with this bitset and destroys the bitset object itself.
Throws: nothing.
Member Functions
void swap(dynamic_bitset& b);Effects: The contents of this bitset and bitset b are exchanged.
Postconditions: This bitset is equal to the original b, and b is equal to the previous version of this bitset.
Throws: nothing.
dynamic_bitset& operator=(const dynamic_bitset& x)Effects: This bitset becomes a copy of the bitset x.
Postconditions: For all i in the range [0,x.size()), (*this)[i] == x[i].
Returns: *this.
Throws: nothing.
(Required by Assignable.)
dynamic_bitset& operator=(dynamic_bitset&& x)Effects: This bitset becomes the same as the bitset x, while using the resources from x.
Postconditions: For all i in the range [0,x.size()), (*this)[i] == x[i].
Returns: *this.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
allocator_type get_allocator() const;Returns: A copy of the allocator object used to construct *this.
void resize(size_type num_bits, bool value = false);Effects: Changes the number of bits of the bitset to num_bits. If num_bits > size() then the bits in the range [0,size()) remain the same, and the bits in [size(),num_bits) are all set to value. If num_bits < size() then the bits in the range [0,num_bits) stay the same (and the remaining bits are discarded).
Postconditions: this->size() == num_bits.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
void clear()Effects: The size of the bitset becomes zero.
Throws: nothing.
void pop_back();Precondition: !this->empty().
Effects: Decreases the size of the bitset by one.
Throws: nothing.
void push_back(bool value);Effects: Increases the size of the bitset by one, and sets the value of the new most-significant bit to value.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
void append(Block value);Effects: Appends the bits in value to the bitset (appends to the most-significant end). This increases the size of the bitset by bits_per_block. Let s be the old size of the bitset, then for i in the range [0,bits_per_block), the bit at position (s + i) is set to ((value >> i) & 1).
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
template <typename BlockInputIterator> void append(BlockInputIterator first, BlockInputIterator last);Effects: This function provides the same end result as the following code, but is typically more efficient.
for (; first != last; ++first) append(*first);Requires: The BlockInputIterator type must be a model of Input Iterator and the value_type must be the same type as Block.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset& operator&=(const dynamic_bitset& rhs)Requires: this->size() == rhs.size().
Effects: Bitwise-AND all the bits in rhs with the bits in this bitset. This is equivalent to:
for (size_type i = 0; i != this->size(); ++i) (*this)[i] = (*this)[i] & rhs[i];Returns: *this.
Throws: nothing.
dynamic_bitset& operator|=(const dynamic_bitset& rhs)Requires: this->size() == rhs.size().
Effects: Bitwise-OR's all the bits in rhs with the bits in this bitset. This is equivalent to:
for (size_type i = 0; i != this->size(); ++i) (*this)[i] = (*this)[i] | rhs[i];Returns: *this.
Throws: nothing.
dynamic_bitset& operator^=(const dynamic_bitset& rhs)Requires: this->size() == rhs.size().
Effects: Bitwise-XOR's all the bits in rhs with the bits in this bitset. This is equivalent to:
for (size_type i = 0; i != this->size(); ++i) (*this)[i] = (*this)[i] ^ rhs[i];Returns: *this.
Throws: nothing.
dynamic_bitset& operator-=(const dynamic_bitset& rhs)Requires: this->size() == rhs.size().
Effects: Computes the set difference of this bitset and the rhs bitset. This is equivalent to:
for (size_type i = 0; i != this->size(); ++i) (*this)[i] = (*this)[i] && !rhs[i];Returns: *this.
Throws: nothing.
dynamic_bitset& operator<<=(size_type n)Effects: Shifts the bits in this bitset to the left by n bits. For each bit in the bitset, the bit at position pos takes on the previous value of the bit at position pos - n, or zero if no such bit exists.
Returns: *this.
Throws: nothing.
dynamic_bitset& operator>>=(size_type n)Effects: Shifts the bits in this bitset to the right by n bits. For each bit in the bitset, the bit at position pos takes on the previous value of bit pos + n, or zero if no such bit exists.
Returns: *this.
Throws: nothing.
dynamic_bitset operator<<(size_type n) constReturns: a copy of *this shifted to the left by n bits. For each bit in the returned bitset, the bit at position pos takes on the value of the bit at position pos - n of this bitset, or zero if no such bit exists.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset operator>>(size_type n) constReturns: a copy of *this shifted to the right by n bits. For each bit in the returned bitset, the bit at position pos takes on the value of the bit at position pos + n of this bitset, or zero if no such bit exists.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset& set()Effects: Sets every bit in this bitset to 1.
Returns: *this
Throws: nothing.
dynamic_bitset& flip()Effects: Flips the value of every bit in this bitset.
Returns: *this
Throws: nothing.
dynamic_bitset operator~() constReturns: a copy of *this with all of its bits flipped.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset& reset()Effects: Clears every bit in this bitset.
Returns: *this
Throws: nothing.
dynamic_bitset& set(size_type n, bool val = true)Precondition: n < this->size().
Effects: Sets bit n if val is true, and clears bit n if val is false.
Returns: *this
dynamic_bitset& reset(size_type n)Precondition: n < this->size().
Effects: Clears bit n.
Returns: *this
dynamic_bitset& flip(size_type n)Precondition: n < this->size().
Effects: Flips bit n.
Returns: *this
size_type size() constReturns: the number of bits in this bitset.
Throws: nothing.
size_type num_blocks() constReturns: the number of blocks in this bitset.
Throws: nothing.
size_type max_size() const;Returns: the maximum size of a dynamic_bitset object having the same type as *this. Note that if any dynamic_bitset operation causes size() to exceed max_size() then the behavior is undefined.
[The semantics of this function could change slightly when lib issue 197 will be closed]
bool empty() const;Returns: true if this->size() == 0, false otherwise. Note: not to be confused with none(), that has different semantics.
size_type capacity() const;Returns: The total number of elements that *this can hold without requiring reallocation.
Throws: nothing.
void reserve(size_type num_bits);Effects: A directive that informs the bitset of a planned change in size, so that it can manage the storage allocation accordingly. After reserve(), capacity() is greater or equal to the argument of reserve() if reallocation happens; and equal to the previous value of capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve().
Note: It does not change the size() of the bitset.
Postcondtitions: this->capacity() >= num_bits.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
void shrink_to_fit();Effects: shrink_to_fit() is a request to reduce memory use by removing unused capacity.
Note: It does not change the size() of the bitset.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
size_type count() constReturns: the number of bits in this bitset that are set.
Throws: nothing.
bool all() constReturns: true if all bits in this bitset are set or if size() == 0, and otherwise returns false.
Throws: nothing.
bool any() constReturns: true if any bits in this bitset are set, and otherwise returns false.
Throws: nothing.
bool none() constReturns: true if no bits are set, and otherwise returns false.
Throws: nothing.
bool test(size_type n) constPrecondition: n < this->size().
Returns: true if bit n is set and false is bit n is 0.
bool test_set(size_type n, bool val = true)Precondition: n < this->size().
Effects: Sets bit n if val is true, and clears bit n if val is false.
Returns: true if the previous state of bit n was set and false is bit n is 0.
reference operator[](size_type n)Precondition: n < this->size().
Returns: a reference to bit n. Note that reference is a proxy class with an assignment operator and a conversion to bool, which allows you to use operator[] for assignment. That is, you can write both x = b[n] and b[n] = x. However, in many other respects the proxy is not the same as the true reference type bool&.
bool operator[](size_type n) constPrecondition: n < this->size().
Returns: The same as test(n).
unsigned long to_ulong() constReturns: The numeric value corresponding to the bits in *this.
Throws: std::overflow_error if that value is too large to be represented in an unsigned long, i.e. if *this has any non-zero bit at a position >= std::numeric_limits<unsigned long>::digits.
bool is_subset_of(const dynamic_bitset& a) constRequires: this->size() == a.size()
Returns: true if this bitset is a subset of bitset a. That is, it returns true if, for every bit that is set in this bitset, the corresponding bit in bitset a is also set. Otherwise this function returns false.
Throws: nothing.
bool is_proper_subset_of(const dynamic_bitset& a) constRequires: this->size() == a.size()
Returns: true if this bitset is a proper subset of bitset a. That is, it returns true if, for every bit that is set in this bitset, the corresponding bit in bitset a is also set and if this->count() < a.count(). Otherwise this function returns false.
Throws: nothing.
bool intersects(const dynamic_bitset& a) constRequires: this->size() == a.size()
Returns: true if this bitset and a intersect. That is, it returns true if, there is a bit which is set in this bitset, such that the corresponding bit in bitset a is also set. Otherwise this function returns false.
Throws: nothing.
size_type find_first() const;Returns: the lowest index i such as bit i is set, or npos if *this has no on bits.
size_type find_next(size_type pos) const;Returns: the lowest index i greater than pos such as bit i is set, or npos if no such index exists.
bool operator==(const dynamic_bitset& rhs) constReturns: true if this->size() == rhs.size() and if for all i in the range [0,rhs.size()), (*this)[i] == rhs[i]. Otherwise returns false.
Throws: nothing.
(Required by Equality Comparable.)
bool operator!=(const dynamic_bitset& rhs) constReturns: !((*this) == rhs)
Throws: nothing.
(Required by Equality Comparable.)
bool operator<(const dynamic_bitset& rhs) constReturns: true if this bitset is lexicographically less than rhs, and returns false otherwise. (See the description of lexicographical_compare for a definition of lexicographic ordering).
Throws: nothing.
(Required by Less Than Comparable.)
bool operator>(const dynamic_bitset& rhs) constReturns: !((*this) < rhs || (*this) == rhs)
Throws: nothing.
(Required by Less Than Comparable.)
bool operator<=(const dynamic_bitset& rhs) constReturns: (*this) < rhs || (*this) == rhs
Throws: nothing.
(Required by Less Than Comparable.)
bool operator>=(const dynamic_bitset& rhs) constReturns: (*this) > rhs || (*this) == rhs
Throws: nothing.
(Required by Less Than Comparable.)
Non-Member Functions
dynamic_bitset operator&(const dynamic_bitset& a, const dynamic_bitset& b)Requires: a.size() == b.size()
Returns: A new bitset that is the bitwise-AND of the bitsets a and b.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset operator|(const dynamic_bitset& a, const dynamic_bitset& b)Requires: a.size() == b.size()
Returns: A new bitset that is the bitwise-OR of the bitsets a and b.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset operator^(const dynamic_bitset& a, const dynamic_bitset& b)Requires: a.size() == b.size()
Returns: A new bitset that is the bitwise-XOR of the bitsets a and b.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
dynamic_bitset operator-(const dynamic_bitset& a, const dynamic_bitset& b)Requires: a.size() == b.size()
Returns: A new bitset that is the set difference of the bitsets a and b.
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator).
template <typename CharT, typename Alloc> void to_string(const dynamic_bitset<Block, Allocator>& b, std::basic_string<Char,Traits,Alloc>& s)Effects: Copies a representation of b into the string s. A character in the string is '1' if the corresponding bit is set, and '0' if it is not. Character position i in the string corresponds to bit position b.size() - 1 - i.
Throws: If memory is exhausted, the string will throw an allocation error.
Rationale: This function is not a member function taking zero arguments and returning a string for a couple reasons. First, this version can be slighly more efficient because the string is not copied (due to being passed by value). Second, as a member function, to allow for flexibility with regards to the template parameters of basic_string, the member function would require explicit template parameters. Few C++ programmers are familiar with explicit template parameters, and some C++ compilers do not handle them properly.
template <typename Block, typename Alloc, typename BlockOutputIterator> void to_block_range(const dynamic_bitset<Block, Alloc>& b, BlockOutputIterator result)Effects: Writes the bits of the bitset into the iterator result a block at a time. The first block written represents the bits in the position range [0,bits_per_block) in the bitset, the second block written the bits in the range [bits_pre_block,2*bits_per_block), and so on. For each block bval written, the bit (bval >> i) & 1 corresponds to the bit at position (b * bits_per_block + i) in the bitset.
Requires: The type BlockOutputIterator must be a model of Output Iterator and its value_type must be the same type as Block. Further, the size of the output range must be greater or equal b.num_blocks().
template <typename BlockIterator, typename Block, typename Alloc> void from_block_range(BlockIterator first, BlockIterator last, const dynamic_bitset<Block, Alloc>& b)Effects: Reads blocks from the iterator range into the bitset.
Requires: The type BlockIterator must be a model of Input Iterator and its value_type must be the same type as Block. The size of the iterator range must be less or equal to b.num_blocks().
template <typename Char, typename Traits, typename Block, typename Alloc> basic_ostream<Char, Traits>& operator<<(basic_ostream<Char, Traits>& os, const dynamic_bitset<Block, Alloc>& b)Effects: Inserts a textual representation of b into the stream os (highest bit first). Informally, the output is the same as doing
std::basic_string<Char, Traits> s; boost::to_string(x, s): os << s;except that the stream inserter takes into accout the locale imbued into os, which boost::to_string() can't do. Here is a more precise specification, given in terms of "as if" rule: first, for each valid position i into the bitset b let's put: character_of(b[i)]) = b[i]? os.widen('1') : os.widen('0'); Let also s be a std::basic_string<Char, Traits> object, having length b.size() and such as, for each i in [0, b.size()), s[i] is character_of(b[i]) Then, the output, the effects on os and the exception behavior is the same as outputting the object s to os (same width, same exception mask, same padding, same setstate() logic)
Returns: os
Throws: std::ios_base::failure if there is a problem writing to the stream.
template <typename Char, typename Traits, typename Block, typename Alloc> std::basic_istream<Char,Traits>& operator>>(std::basic_istream<Char,Traits>& is, dynamic_bitset<Block, Alloc>& b)Effects: Extracts a dynamic_bitset from an input stream.
Definitions:
Let Tr be the traits_type of is. Then:
- c, извлеченный из, являетсябитсетной цифрой, если и только если Tr::eq(c, is.widen('0')) или Tr::eq(c, is.widen('1')) возвращают истинное значение.
- Если c — битовая цифра, тосоответствующее битовое значениеравно 0, если Tr::eq(c, is.widen('0')) истинно, 1 иначе.
- nбиты хранятся в битсете;
- конец файла, или ошибка, происходит на входной последовательности;
- Следующий доступный входной символ не является битсетной цифрой
If no exception caused the function to exit then is.width(0) is called, regardless of how many characters were actually extracted. The sentry object k is destroyed.
If the function extracts no characters[???], it calls is.setstate(std::ios::failbit), which may throw std::ios_base::failure.
------
Throws: An allocation error if memory is exhausted (std::bad_alloc if Allocator=std::allocator). A std::ios_base::failure if there is a problem reading from the stream.
Exception guarantees
All of dynamic_bitset functions offer at least the basic exception guarantee.Changes from previous version(s)
Changes in Boost 1.56.0
- Поддержка конструкторов C++11.
- Предупреждение по MSVC 2013.
- Поддержка минимальных распределителей C++11.
- Добавьте только спецификации.
Changes in Boost 1.37.0
- Конструктор из диапазона блоков реализует поведение «делать правильные вещи», стандартные последовательности.
Changes from Boost 1.31.0
- Экстрактор потока имеет совершенно другую семантику: как естественная для динамической структуры, он теперь расширяет битсет по мере необходимости во время экстракции. Новое поведение имитирует поведение экстрактораbasic_string, но есть некоторые различия, о которых пользователь должен знать; поэтому, пожалуйста, проверьте документацию. (Одно отличие касается случая, когда
stream.width() > bitset.max_size() > 0
). В этом случае экстракторDynamic_bitsetникогда не пытается извлечь большесимволов max_size(), тогда как экстракторbasic_stringпродолжается и, на соответствующих реализациях, в конечном итоге бросаетlong_errorисключение. Примечание: Это то, что стандартные мандаты - см. особеннобиблиотечный выпуск 83- но не все реализации соответствуют
Экстрактор потока теперь также «осознает исключение» в том смысле, что он работает правильно при установке масок исключения на потоке. - Было добавлено несколько функций (пустой(),find_first(),find_next(),get_allocator(),intersects(),max_size()reserve(),capacity()-->).) have been added. [ORIG_END] -->
- Конструктор изbasic_stringимеет новый параметр, который был полностью забыт ранее.
- Ссылка на классбыла реализована таким образом, что ссылки динамического битсета ведут себя скорее как ссылки на стандартные элементы контейнера. В частности, теперь гарантируется, что они не могут быть признаны недействительными из стандартной функции обмена библиотеками, применяемой к их соответствующемудинамическому_битсету.
- Несколько оптимизаций для функций-членов и не-членов и для вложенного классассылка.
See also
std::bitset, std::vector,Acknowledgements
Мы хотели бы поблагодарить сообщество Boost за предоставленное время для рассмотрения и принятия этой библиотеки. Эта библиотека намного лучше, чем когда-либо, благодаря всем предложениям членов Boost. Мы особенно благодарим Мэтта Маркуса за то, что он взял на себя задачу менеджера по обзору. Особая благодарность Джеймсу Канзе за его неоценимую помощь в вопросах интернационализации.
Copyright & Copy; 2001 | Джереми Сик, Университет Индианыjsiek@osl.iu.edu] Чак Эллисон, старший редактор, C/C++ Users Journalcda@freshsources.com |
Copyright © 2003-2004, 2008 | Геннаро Прота(имя.фамилия yahoo.com) |
Copyright & Copy, 2014 | Ахмед Чарльз (acharles@outlook.com) |
Copyright & Copy, 2014 | Глен Фернандес (glenfe@live.com) |
Copyright & Copy, 2014 | Риккардо Марканджело (ricky.65@outlook.com) |