namespaceboost{namespacemulti_index{// index specifiers hashed_unique and hashed_non_uniquetemplate<consult hashed_unique reference for arguments>structhashed_unique;template<consult hashed_non_unique reference for arguments>structhashed_non_unique;// indicesnamespacedetail{template<implementation defined>classindex name is implementation defined;}// namespace boost::multi_index::detail}// namespace boost::multi_index}// namespace boost
#include<initializer_list>namespaceboost{namespacemulti_index{// index specifiers hashed_unique and hashed_non_uniquetemplate<consult hashed_unique reference for arguments>structhashed_unique;template<consult hashed_non_unique reference for arguments>structhashed_non_unique;// indicesnamespacedetail{template<implementation defined>classindex class name implementation defined;// index comparison:// OP is any of ==,!=template<implementation defined>booloperatorOP(constindex class name&x,constindex class name&y);// index specialized algorithms:template<implementation defined>voidswap(index class name&x,index class name&y);}// namespace boost::multi_index::detail}// namespace boost::multi_index}// namespace boost
Этиуказатели индексовпозволяют вставлятьхешированные индексыбез и с учетом дублирующих элементов, соответственно. Синтаксис<hashed_unique>и<hashed_non_unique>совпадают, поэтому мы описываем их сгруппированным образом.<hashed_unique>и<hashed_non_unique>могут быть представлены в двух различных формах, в зависимости от того, предоставляется ли список тегов для индекса:
Если это так, то<TagList>должно быть преобразовано в<tag>. Аргументы шаблона используются соответствующей реализацией индекса, ссылаясь на раздел ссылкихешированных индексовдля дальнейших объяснений их приемлемых значений типа.
Хешированный индекс обеспечивает быстрое извлечение элементов<multi_index_container>с помощью методов хеширования. Указатель хеширования конкретизируется в соответствии с данным<Key Extractor>, который извлекает ключи из элементов<multi_index_container>, объектом функции<Hash>, который возвращает хеш-значения для ключей и двоичным предикатом<Pred>, действующим как отношение эквивалентности на значениях<Key>.
Существует два варианта хешированных индексов:уникальный, которые не допускают дублирования элементов (по отношению к связанному с ним предикату равенства) инеуникальный, которые принимают эти дубликаты. Интерфейс этих двух вариантов одинаков, поэтому они документируются вместе с небольшими различиями, явно выраженными при их существовании.
За исключением случаев, когда отмечен или если соответствующий интерфейс не существует, хешированные индексы (как уникальные, так и неуникальные) удовлетворяют требованиям C++ для неупорядоченных ассоциативных контейнеров[unord.req](поддержка уникальных и эквивалентных ключей, соответственно). Действительность итераторов и отсылок к элементам сохраняется во всех случаях. Иногда предоставленные гарантии безопасности исключения на самом деле сильнее, чем требуется стандартом. Мы предоставляем только описания тех типов и операций, которые не соответствуют или не соответствуют стандартным требованиям.
namespaceboost{namespacemulti_index{namespacedetail{template<implementation defined: dependent on types Value, Allocator,
TagList, KeyFromValue, Hash, Pred>classname is implementation defined{public:// types:typedeftypenameKeyFromValue::result_typekey_type;typedefValuevalue_type;typedefKeyFromValuekey_from_value;typedefHashhasher;typedefPredkey_equal;typedefboost::tuple<size_type,key_from_value,hasher,key_equal>ctor_args;typedefTagListtag_list;typedefAllocatorallocator_type;typedeftypenameAllocator::pointerpointer;typedeftypenameAllocator::const_pointerconst_pointer;typedeftypenameAllocator::referencereference;typedeftypenameAllocator::const_referenceconst_reference;typedefimplementation defined size_type;typedefimplementation defined difference_type;typedefimplementation defined iterator;typedefimplementation defined const_iterator;typedefimplementation defined local_iterator;typedefimplementation defined const_local_iterator;// construct/destroy/copy:index class name&operator=(constindex class name&x);index class name&operator=(std::initializer_list<value_type>list);allocator_typeget_allocator()constnoexcept;// size and capacity:boolempty()constnoexcept;size_typesize()constnoexcept;size_typemax_size()constnoexcept;// iterators:iteratorbegin()noexcept;const_iteratorbegin()constnoexcept;iteratorend()noexcept;const_iteratorend()constnoexcept;const_iteratorcbegin()const;const_iteratorcend()const;iteratoriterator_to(constvalue_type&x);const_iteratoriterator_to(constvalue_type&x)const;// modifiers:template<typename...Args>std::pair<iterator,bool>emplace(Args&&...args);template<typename...Args>iteratoremplace_hint(iteratorposition,Args&&...args);std::pair<iterator,bool>insert(constvalue_type&x);std::pair<iterator,bool>insert(value_type&&x);iteratorinsert(iteratorposition,constvalue_type&x);iteratorinsert(iteratorposition,value_type&&x);template<typenameInputIterator>voidinsert(InputIteratorfirst,InputIteratorlast);voidinsert(std::initializer_list<value_type>list);iteratorerase(iteratorposition);size_typeerase(constkey_type&x);iteratorerase(iteratorfirst,iteratorlast);boolreplace(iteratorposition,constvalue_type&x);boolreplace(iteratorposition,value_type&&x);template<typenameModifier>boolmodify(iteratorposition,Modifiermod);template<typenameModifier,typenameRollback>boolmodify(iteratorposition,Modifiermod,Rollbackback);template<typenameModifier>boolmodify_key(iteratorposition,Modifiermod);template<typenameModifier,typenameRollback>boolmodify_key(iteratorposition,Modifiermod,Rollbackback);voidclear()noexcept;voidswap(index class name&x);// observers:key_from_valuekey_extractor()const;hasherhash_function()const;key_equalkey_eq()const;// lookup:template<typenameCompatibleKey>iteratorfind(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleHash,typenameCompatiblePred>iteratorfind(constCompatibleKey&x,constCompatibleHash&hash,constCompatiblePred&eq)const;template<typenameCompatibleKey>size_typecount(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleHash,typenameCompatiblePred>size_typecount(constCompatibleKey&x,constCompatibleHash&hash,constCompatiblePred&eq)const;template<typenameCompatibleKey>std::pair<iterator,iterator>equal_range(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleHash,typenameCompatiblePred>std::pair<iterator,iterator>equal_range(constCompatibleKey&x,
constCompatibleHash&hash,constCompatiblePred&eq)const;// bucket interface:size_typebucket_count()constnoexcept;size_typemax_bucket_count()constnoexcept;size_typebucket_size(size_typen)const;size_typebucket(constkey_type&k)const;local_iteratorbegin(size_typen);const_local_iteratorbegin(size_typen)const;local_iteratorend(size_typen);const_local_iteratorend(size_typen)const;const_local_iteratorcbegin(size_typen)const;const_local_iteratorcend(size_typen)const;local_iteratorlocal_iterator_to(constvalue_type&x);const_local_iteratorlocal_iterator_to(constvalue_type&x)const;// hash policy:floatload_factor()constnoexcept;floatmax_load_factor()constnoexcept;voidmax_load_factor(floatz);voidrehash(size_typen);voidreserve(size_typen);};// index comparison:template<implementation defined>booloperator==(constindex class name&x,constindex class name&y);template<implementation defined>booloperator!=(constindex class name&x,constindex class name&y){return!(x==y);}// index specialized algorithms:template<implementation defined>voidswap(index class name&x,index class name&y);}// namespace boost::multi_index::detail}// namespace boost::multi_index}// namespace boost
<TagList>должно быть инстанциацией<tag>. Тип<KeyFromValue>, определяющий механизм извлечения ключа из<Value>, должен быть образцом<Key Extractor>из<Value>.<Hash>является<CopyConstructible>унарным функциональным объектом, принимающим один аргумент типа<KeyFromValue::result_type>и возвращающим значение типа<std::size_t>в диапазоне<[0, std::numeric_limits<std::size_t>::max())>.<Pred>является<CopyConstructible>двоичным предикатом, индуцирующим отношение эквивалентности на элементах<KeyFromValue::result_type>. Требуется, чтобы<Hash>объект возвращал то же значение для ключей, эквивалентное<Pred>.Valueизmulti_index_container,
Allocatorизmulti_index_container,
TagListиз указателя индекса (если предусмотрено, в противном случае предполагаетсяtag<>),
KeyFromValueиз указателя индекса,
Hashиз указателя индекса,
Predиз указателя индекса.
TagList must be an instantiation of
tag. The type KeyFromValue,
which determines the mechanism for extracting a key from Value,
must be a model of Key Extractor from Value. Hash is a
CopyConstructibleunary function object
taking a single argument of type KeyFromValue::result_type and returning a
value of type std::size_t in the range
[0, std::numeric_limits<std::size_t>::max()).
Pred is a CopyConstructible binary predicate inducing an equivalence relation
on elements of KeyFromValue::result_type. It is required that
the Hash object return the same value for keys
equivalent under Pred.
[ORIG_END] -->
The first element of this tuple indicates the minimum number of buckets
set up by the index on construction time. If the default value 0 is used,
an implementation defined number is used instead.
Как поясняется в разделе 122 концепции индексов, индексы не имеют публичных конструкторов или деструкторов. Присвоение, с другой стороны, предусмотрено. При строительстве<max_load_factor()>составляет 1,0.
index class name& operator=(const index class name& x);
Effects:
a=b;
where a and b are the multi_index_container
objects to which *this and x belong, respectively. Returns:*this.
index class name& operator=(std::initializer_list<value_type> list);
Effects:
a=list;
where a is the multi_index_container
object to which *this belongs. Returns:*this.
Requires:value_type is EmplaceConstructible
into multi_index_container from args. Effects: Inserts a value_type object constructed with
std::forward<Args>(args)... into the multi_index_container to which
the index belongs if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
И вставка допускается всеми другими индексамиmulti_index_container.
Returns: The return value is a pair p. p.second
is true if and only if insertion took place. On successful insertion,
p.first points to the element inserted; otherwise, p.first
points to an element that caused the insertion to be banned. Note that more than
one element can be causing insertion not to be allowed. Complexity:O(I(n)). Exception safety: Strong, except that rehashing may occur even if the operation fails.
Requires:value_type is EmplaceConstructible
into multi_index_container from args.
position is a valid iterator of the index. Effects: Inserts a value_type object constructed with
std::forward<Args>(args)... into the multi_index_container to which
the index belongs if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
И вставка допускается всеми другими индексамиmulti_index_container.
position is used as a hint to improve the efficiency of the
operation. Returns: On successful insertion, an iterator to the newly inserted
element. Otherwise, an iterator to an element that caused the insertion to be
banned. Note that more than one element can be causing insertion not to be
allowed. Complexity:O(H(n)). Exception safety: Strong, except that rehashing may occur even if the operation fails.
Requires (first version):value_type is CopyInsertable
into multi_index_container. Requires (second version):value_type is MoveInsertable
into multi_index_container. Effects: Inserts x into the multi_index_container to which
the index belongs if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
И вставка допускается всеми другими индексамиmulti_index_container.
Returns: The return value is a pair p. p.second
is true if and only if insertion took place. On successful insertion,
p.first points to the element inserted; otherwise, p.first
points to an element that caused the insertion to be banned. Note that more than
one element can be causing insertion not to be allowed. Complexity:O(I(n)). Exception safety: Strong, except that rehashing may occur even if the operation fails.
Requires (first version):value_type is CopyInsertable
into multi_index_container.
position is a valid iterator of the index. Requires (second version):value_type is MoveInsertable
into multi_index_container.
position is a valid iterator of the index. Effects: Inserts x into the multi_index_container to which
the index belongs if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
И вставка допускается всеми другими индексамиmulti_index_container.
position is used as a hint to improve the efficiency of the
operation. Returns: On successful insertion, an iterator to the newly inserted
element. Otherwise, an iterator to an element that caused the insertion to be
banned. Note that more than one element can be causing insertion not to be
allowed. Complexity:O(H(n)). Exception safety: Strong, except that rehashing may occur even if the operation fails.
Requires:InputIterator is an input iterator.
value_type is
EmplaceConstructible into
multi_index_container from *first.
first and last are not iterators into any
index of the multi_index_container to which this index belongs.
last is reachable from first. Effects:
For each element of [first, last), in this
order, inserts it into the multi_index_container
to which this index belongs if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
И вставка допускается всеми другими индексамиmulti_index_container.
Complexity:O(m*I(n+m)), where
m is the number of elements in [first,
last). Exception safety: Basic.
Requires:position is a valid dereferenceable iterator
of the index. Effects: Deletes the element pointed to by position. Returns: An iterator pointing to the element immediately following
the one that was deleted, or end()
if no such element exists. Complexity:O(D(n)). Exception safety:nothrow.
size_type erase(const key_type& x);
Effects: Deletes the elements with key equivalent to x. Returns: Number of elements deleted. Complexity: Average case, O(1 + m*D(n)), worst case
O(ndist + m*D(n)), where m is
the number of elements deleted. Exception safety: Basic.
iterator erase(iterator first,iterator last);
Requires: [first,last) is a valid
range of the index. Effects: Deletes the elements in [first,last). Returns:last. Complexity:O(m*D(n)), where m is
the number of elements in [first,last). Exception safety:nothrow.
Requires (first version):value_type is CopyAssignable.
position is a valid dereferenceable iterator of the index. Requires (second version):value_type is MoveAssignable.
position is a valid dereferenceable iterator of the index. Effects: Assigns the value x to the element pointed
to by position into the multi_index_container to which
the index belongs if, for the value x
индекс не является уникальным или не существует другого элемента (за исключением, возможно,*position) с эквивалентным ключом;
И замена допускается всеми другими индексамиmulti_index_container.
Postconditions: Validity of position is preserved
in all cases. If the key of the new value is equivalent to that of the replaced value,
the position of the element does not change. Returns:true if the replacement took place,
false otherwise. Complexity:O(R(n)). Exception safety: Strong. If an exception is thrown by some
user-provided operation the multi_index_container to which the index
belongs remains in its original state.
Requires:mod is a unary function object
accepting arguments of type
value_type&. position is a valid dereferenceable
iterator of the index.
The execution of mod(e), where e is the element
pointed to by position, does not invoke any operation of the
multi_index_container after e is directly modified
or, before modification, if the operation would invalidate position. Effects: Calls mod(e) where e is the element
pointed to by position and rearranges *position into
all the indices of the multi_index_container. Rearrangement is successful if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
Перестройка допускается всеми другими индексамиmulti_index_container.
If the rearrangement fails, the element is erased. Postconditions: Validity of position is preserved if the
operation succeeds. If the key of the modified value is equivalent to that of the
original value, the position of the element does not change. Returns:true if the operation succeeded, false
otherwise. Complexity:O(M(n)). Exception safety: Basic. If an exception is thrown by some
user-provided operation (except possibly mod), then
the element pointed to by position is erased.
Requires:mod and back are unary function
objects accepting arguments of type
value_type&. position is a valid dereferenceable
iterator of the index.
The execution of mod(e), where e is the element
pointed to by position, does not invoke any operation of the
multi_index_container after e is directly modified
or, before modification, if the operation would invalidate position.
back(e) does not invoke any operation of the
multi_index_container.
The sequence of operations mod(e),
back(e) restores all keys of the element
to their original state. Effects: Calls mod(e) where e is the element
pointed to by position and tries to rearrange *position into
all the indices of the multi_index_container. Rearrangement is successful if
индекс не является уникальным или не существует другого элемента с эквивалентным ключом;
Перестройка допускается всеми другими индексамиmulti_index_container.
If the rearrangement fails, back(e) is invoked and the
element is kept at its original position in all indices. Postconditions: Validity of position is preserved except if
the element is erased under the conditions described below.
If the key of the modified value is equivalent to that of the
original value, the position of the element does not change. Returns:true if the operation succeeded, false
otherwise. Complexity:O(M(n)). Exception safety: Strong, except if back throws an
exception, in which case the modified element is erased. If back
throws inside the handling code executing after some other user-provided
operation has thrown, it is the exception generated by back that
is rethrown.
Requires:key_from_value is a read/write
Key Extractor
from value_type. mod is a
unary function object accepting arguments of type
key_type&. position is a valid dereferenceable
iterator of the index.
The execution of mod(k), where k is the key of the element
pointed to by position, does not invoke any operation of the
multi_index_container after k is directly modified
or, before modification, if the operation would invalidate position. Effects: Equivalent to modify(position,mod'),
with mod' defined in such a way that
mod'(x) is the same as mod(key(x)), where
key is the internal KeyFromValue object of the index.
Requires:key_from_value is a read/write
Key Extractor
from value_type. mod and back
are unary function objects accepting arguments of type
key_type&. position is a valid dereferenceable
iterator of the index.
The execution of mod(k), where k is the key of the element
pointed to by position, does not invoke any operation of the
multi_index_container after k is directly modified
or, before modification, if the operation would invalidate position.
back(k) does not invoke any operation of the
multi_index_container.
The sequence of operations mod(k),
back(k) restores k to its original state. Effects: Equivalent to modify(position,mod',back'),
with mod' and back defined in such a way that
mod'(x) is the same as mod(key(x)) and
back'(x) is the same as back(key(x)), where
key is the internal KeyFromValue object of the index.
Индексы хеширования обеспечивают полную функциональность поиска, требуемую[unord.req], а именно<find>,<count>и<equal_range>. Кроме того, эти функции членов шаблонизированы, чтобы обеспечить нестандартные аргументы, таким образом расширяя типы разрешенных поисковых операций. Вид аргументов, допустимых при вызове функций поиска, определяется следующей концепцией.
Рассмотрим пару<Hash>,<Pred>, где<Hash>является хеш-функтором над значениями типа<Key>и<Pred>является двоичным предикатом, индуцирующим отношение эквивалентности на<Key>, с дополнительным ограничением, что эквивалентные ключи имеют одинаковое хеш-значение. Триплет типов [<CompatibleKey>,<CompatibleHash>,<CompatiblePred>] называетсясовместимым расширением[<Hash>,<Pred>], если
for every c_hash of type CompatibleHash,
c_eq of type CompatiblePred,
hash of type Hash,
eq of type Pred, ck of type
CompatibleKey and k1, k2 of type
Key.
[ORIG_END] -->
Кроме того, тип<CompatibleKey>называетсясовместимым ключом<Hash>,<Pred>, если<CompatibleKey>,<Hash>,<Pred>является совместимым расширением<Hash>,<Pred>. Это означает, что<Hash>и<Pred>принимают аргументы типа<CompatibleKey>, что обычно означает, что они имеют несколько перегрузок своих соответствующих<operator()>функций-членов.
В контексте совместимого расширения или совместимого ключа выражение «эквивалентный ключ» принимает свою очевидную интерпретацию.
Requires:CompatibleKey is a compatible key of
(hasher, key_equal). Effects: Returns a pointer to an element whose key is equivalent to
x, or end() if such an element does not exist. Complexity: Average case O(1) (constant), worst case
O(ndist).
Requires: (CompatibleKey, CompatibleHash,
CompatiblePred) is a compatible extension of
(hasher, key_equal). Effects: Returns a pointer to an element whose key is equivalent to
x, or end() if such an element does not exist. Complexity: Average case O(1) (constant), worst case
O(ndist).
Requires:CompatibleKey is a compatible key of
(hasher, key_equal). Effects: Returns the number of elements with key equivalent to x. Complexity: Average case O(count(x)), worst case
O(count(x)+ndist).
Requires: (CompatibleKey, CompatibleHash,
CompatiblePred) is a compatible extension of
(hasher, key_equal). Effects: Returns the number of elements with key equivalent to x. Complexity: Average case O(count(x,hash,eq)), worst case
O(count(x,hash,eq)+ndist).
Requires:CompatibleKey is a compatible key of
(hasher, key_equal). Effects: Returns a range containing all elements with keys equivalent
to x (and only those), or (end(),end())
if no such elements exist. Complexity: Average case O(1) (constant), worst case
O(ndist).
Requires: (CompatibleKey, CompatibleHash,
CompatiblePred) is a compatible extension of
(hasher, key_equal). Effects: Returns a range containing all elements with keys equivalent
to x (and only those), or (end(),end())
if no such elements exist. Complexity: Average case O(1) (constant), worst case
O(ndist).
Effects: Increases if necessary the number of internal buckets
so that size()/bucket_count() does not exceed the maximum
load factor, and bucket_count()>=n. Postconditions: Validity of iterators and references to the
elements contained is preserved. Complexity:O(m), where m is the number of
non-equivalent elements in the index. Exception safety: Strong.
template<implementation defined>
bool operator==(const index class name& x,const index class name& y);
Requires:x.key_extractor(), x.hash_function() and
x.key_eq() have the same behavior as the corresponding objects in y.
For any two elements e1, e2 in x or y,
if e1==e2 then their keys are equivalent. Returns:true iff x and y have the same size
and for each key k present in x the range
x.equal_range(k) is equal (considering the == operator of value_type)
to y.equal_range(k) under permutations of the elements. Complexity: Let k1,...,km be the different
keys present in x:
Если для каждогоkix.equal_range(ki)устроено в том же порядке, что иy.equal_range(ki), средний случайO(x.size()), наихудший случайO(x.size()2).
В противном случае средний случайO(Σ(x.count(ki)2)), худший случайO(x.size()2).
(For unique indices, the formulas above reduce to average case
O(x.size()), worst case O(x.size()2).)
Индексы не могут быть сериализованы сами по себе, но только как часть<multi_index_container>, в которую они встроены. При описании дополнительных предварительных условий и гарантий, связанных с хешированными индексами в отношении сериализации их встраиваемых контейнеров, мы используем понятия, определенные в<multi_index_container>.Раздел сериализации.
Operation: saving of a multi_index_containerm to an
output archive (XML archive) ar.
Requires: No additional requirements to those imposed by the container.
Operation: loading of a multi_index_containerm' from an
input archive (XML archive) ar.
Requires: Additionally to the general requirements, key_eq()
must be serialization-compatible with m.get<i>().key_eq(),
where i is the position of the hashed index in the container. Postconditions: On successful loading, the range
[begin(), end()) contains restored copies of every
element in [m.get<i>().begin(), m.get<i>().end()),
though not necessarily in the same order.
Operation: saving of an iterator or const_iteratorit to an output archive (XML archive) ar.
Requires:it is a valid iterator of the index. The associated
multi_index_container has been previously saved.
Operation: loading of an iterator or const_iteratorit' from an input archive (XML archive) ar.
Postconditions: On successful loading, if it was dereferenceable
then *it' is the restored copy of *it, otherwise
it'==end(). Note: It is allowed that it be a const_iterator
and the restored it' an iterator, or vice versa.
Operation: saving of a local_iterator or
const_local_iteratorit to an output archive (XML archive) ar.
Requires:it is a valid local iterator of the index. The
associated multi_index_container has been previously saved.
Operation: loading of a local_iterator or
const_local_iteratorit' from an input archive (XML archive) ar.
Postconditions: On successful loading, if it was dereferenceable
then *it' is the restored copy of *it; if it
was m.get<i>().end(n) for some n, then
it'==m'.get<i>().end(n) (where m is the original
multi_index_container, m' its restored copy
and i is the ordinal of the index.) Note: It is allowed that it be a const_local_iterator
and the restored it' a local_iterator, or vice versa.
Статья Boost.MultiIndex Documentation - Hashed indices reference раздела Boost.MultiIndex Documentation - Reference может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.