namespaceboost{namespacemulti_index{// index specifiers ordered_unique and ordered_non_uniquetemplate<consult ordered_unique reference for arguments>structordered_unique;template<consult ordered_non_unique reference for arguments>structordered_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 ordered_unique and ordered_non_uniquetemplate<consult ordered_unique reference for arguments>structordered_unique;template<consult ordered_non_unique reference for arguments>structordered_non_unique;// indicesnamespacedetail{template<implementation defined>classindex class name implementation defined;// index comparison:// OP is any of ==,<,!=,>,>=,<=template<arg set 1,arg set 2>booloperatorOP(constindex class name<arg set 1>&x,constindex class name<arg set 2>&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
Этиуказатели индексовпозволяют вставлятьупорядоченные индексыбез и с учетом дублирующих элементов, соответственно. Синтаксис<ordered_unique>и<ordered_non_unique>совпадают, поэтому мы описываем их сгруппированным образом.<ordered_unique>и<ordered_non_unique>могут быть представлены в двух различных формах, в зависимости от того, предоставляется ли список тегов для индекса:
Если это так, то<TagList>должно быть преобразовано в<tag>. Аргументы шаблона используются соответствующей реализацией индекса, ссылаясь на раздел ссылкиупорядоченных индексовдля дальнейших объяснений их приемлемых значений типа.
Упорядоченный индекс обеспечивает заданный интерфейс к основной куче элементов, содержащихся в<multi_index_container>. Упорядоченный индекс конкретизируется согласно заданному<Key Extractor>, который извлекает ключи из элементов<multi_index_container>и сравнительного предиката.
Существует два варианта упорядоченных индексов:уникальный, не допускающий дублирования элементов (по отношению к связанному с ним сравнительному предикату) инеуникальный, принимающий эти дубликаты. Интерфейс этих двух вариантов одинаков, поэтому они документируются вместе с небольшими различиями, явно выраженными при их существовании.
За исключением случаев, когда отмечен или если соответствующий интерфейс не существует, упорядоченные индексы (как уникальные, так и неуникальные) удовлетворяют требованиям C++ для ассоциативных контейнеров по адресу[associative.reqmts].(поддержка уникальных и эквивалентных ключей, соответственно). Соответственно сохраняется валидность итераторов и ссылок на элементы. Мы предоставляем только описания тех типов и операций, которые не соответствуют или не соответствуют стандартным требованиям.
namespaceboost{namespacemulti_index{implementation defined unbounded;// see range()namespacedetail{template<implementation defined: dependent on types Value, Allocator,
TagList, KeyFromValue, Compare>classname is implementation defined{public:// types:typedeftypenameKeyFromValue::result_typekey_type;typedefValuevalue_type;typedefKeyFromValuekey_from_value;typedefComparekey_compare;typedefimplementation defined value_compare;typedefboost::tuple<key_from_value,key_compare>ctor_args;typedefTagListtag_list;typedefAllocatorallocator_type;typedeftypenameAllocator::referencereference;typedeftypenameAllocator::const_referenceconst_reference;typedefimplementation defined iterator;typedefimplementation defined const_iterator;typedefimplementation defined size_type;typedefimplementation defined difference_type;typedeftypenameAllocator::pointerpointer;typedeftypenameAllocator::const_pointerconst_pointer;typedefequivalent to
std::reverse_iterator<iterator>reverse_iterator;typedefequivalent to
std::reverse_iterator<const_iterator>const_reverse_iterator;// construct/copy/destroy:index class name&operator=(constindex class name&x);index class name&operator=(std::initializer_list<value_type>list);allocator_typeget_allocator()constnoexcept;// iterators:iteratorbegin()noexcept;const_iteratorbegin()constnoexcept;iteratorend()noexcept;const_iteratorend()constnoexcept;reverse_iteratorrbegin()noexcept;const_reverse_iteratorrbegin()constnoexcept;reverse_iteratorrend()noexcept;const_reverse_iteratorrend()constnoexcept;const_iteratorcbegin()constnoexcept;const_iteratorcend()constnoexcept;const_reverse_iteratorcrbegin()constnoexcept;const_reverse_iteratorcrend()constnoexcept;iteratoriterator_to(constvalue_type&x);const_iteratoriterator_to(constvalue_type&x)const;// capacity:boolempty()constnoexcept;size_typesize()constnoexcept;size_typemax_size()constnoexcept;// 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);voidswap(index class name&x);voidclear()noexcept;// observers:key_from_valuekey_extractor()const;key_comparekey_comp()const;value_comparevalue_comp()const;// set operations:template<typenameCompatibleKey>iteratorfind(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>iteratorfind(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>size_typecount(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>size_typecount(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>iteratorlower_bound(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>iteratorlower_bound(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>iteratorupper_bound(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>iteratorupper_bound(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>std::pair<iterator,iterator>equal_range(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>std::pair<iterator,iterator>equal_range(constCompatibleKey&x,constCompatibleCompare&comp)const;// range:template<typenameLowerBounder,typenameUpperBounder>std::pair<iterator,iterator>range(LowerBounderlower,UpperBounderupper)const;};// index comparison:template<arg set 1,arg set 2>booloperator==(constindex class name<arg set 1>&x,constindex class name<arg set 2>&y){returnx.size()==y.size()&&std::equal(x.begin(),x.end(),y.begin());}template<arg set 1,arg set 2>booloperator<(constindex class name<arg set 1>&x,constindex class name<arg set 2>&y){returnstd::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end());}template<arg set 1,arg set 2>booloperator!=(constindex class name<arg set 1>&x,constindex class name<arg set 2>&y){return!(x==y);}template<arg set 1,arg set 2>booloperator>(constindex class name<arg set 1>&x,constindex class name<arg set 2>&y){returny<x;}template<arg set 1,arg set 2>booloperator>=(constindex class name<arg set 1>&x,constindex class name<arg set 2>&y){return!(x<y);}template<arg set 1,arg set 2>booloperator<=(constindex class name<arg set 1>&x,constindex class name<arg set 2>&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>.<Compare>представляет собой<CopyConstructible>двоичный предикат, вызывающий строгий слабый порядок на элементах<KeyFromValue::result_type>.Valueизmulti_index_container,
Allocatorизmulti_index_container,
TagListиз указателя индекса (если предусмотрено, в противном случаеtag<>предполагается),
KeyFromValueиз указателя индекса,
Compareиз указателя индекса.
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. Compare is a
CopyConstructible binary predicate inducing a strict weak order
on elements of KeyFromValue::result_type.
[ORIG_END] -->
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.
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. If successful, insertion happens as close as possible to the
location just prior to position. 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.
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.
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. If successful, insertion happens as close as possible to the
location just prior to position. 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.
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*H(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:O(log(n) + 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(log(n) + 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.
Упорядоченные индексы обеспечивают полную функциональность поиска, требуемую[associative.reqmts], а именно<find>,<count>,<lower_bound>,<upper_bound>и<equal_range>. Кроме того, эти функции членов шаблонизированы, чтобы обеспечить нестандартные аргументы, таким образом расширяя типы разрешенных поисковых операций. Вид аргументов, допустимых при вызове функций поиска, определяется следующей концепцией.
Рассмотрим двоичный предикат<Compare>, индуцирующий строгий слабый порядок над значениями типа<Key>. Пара типов [<CompatibleKey>,<CompatibleCompare>] называетсясовместимым расширением<Compare>, если
для каждого<c_comp>типа<CompatibleCompare>,<comp>типа<Compare>,<ck>типа<CompatibleKey>и<k1>,<k2>типа<Key>.CompatibleCompare— двоичный предикат надKey,CompatibleKey,
for every c_comp of type CompatibleCompare,
comp of type Compare, ck of type
CompatibleKey and k1, k2 of type
Key.
[ORIG_END] -->
Кроме того, тип<CompatibleKey>называетсясовместимым ключом<Compare>, если<CompatibleKey>,<Compare>является совместимым расширением<Compare>. Это означает, что<Compare>, а также будучи строгим слабым упорядочением, принимает аргументы типа<CompatibleKey>, что обычно означает, что он имеет несколько перегрузок<operator()>.
В контексте совместимого расширения или совместимого ключа выражения «эквивалент», «меньше чем» и «больше чем» принимают свои очевидные интерпретации.
Requires:CompatibleKey is a compatible key of
key_compare. Effects: Returns a pointer to an element whose key is equivalent to
x, or end() if such an element does not exist. Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Returns a pointer to an element whose key is equivalent to
x, or end() if such an element does not exist. Complexity:O(log(n)).
Requires:CompatibleKey is a compatible key of
key_compare. Effects: Returns the number of elements with key equivalent to x. Complexity:O(log(n) + count(x)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Returns the number of elements with key equivalent to x. Complexity:O(log(n) + count(x,comp)).
Requires:CompatibleKey is a compatible key of
key_compare. Effects: Returns an iterator pointing to the first element with
key not less than x, or end() if such an element does
not exist. Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Returns an iterator pointing to the first element with
key not less than x, or end() if such an element does
not exist. Complexity:O(log(n)).
Requires:CompatibleKey is a compatible key of
key_compare. Effects: Returns an iterator pointing to the first element with
key greater than x, or end() if such an element does
not exist. Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Returns an iterator pointing to the first element with
key greater than x, or end() if such an element does
not exist. Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Equivalent to
make_pair(lower_bound(x,comp),upper_bound(x,comp)). Complexity:O(log(n)).
Функция члена<range>не определена для сортированных ассоциативных контейнеров, но упорядоченные индексы обеспечивают ее как удобную утилиту. Диапазон или интервал определяется двумя условиями для нижней и верхней границ, которые моделируются после следующих понятий.
Рассмотрим двоичный предикат<Compare>, индуцирующий строгий слабый порядок над значениями типа<Key>. Тип<LowerBounder>называетсянижним граничником<Compare>, если
< [132] >[< [133] >] [< [132] >] [< [133] >]
< [136] >и< [137] >,< [138] >,
для каждого<lower>типа<LowerBounder>,<comp>типа<Compare>и<k1>,<k2>типа<Key>. Точно так жеверхняя границаявляется типом<UpperBounder>таким, что
для каждого<upper>типа<UpperBounder>,<comp>типа<Compare>и<k1>,<k2>типа<Key>.LowerBounderявляется предикатомKey,
Еслиlower(k1)и!comp(k2,k1), тоlower(k2)
for every lower of type LowerBounder,
comp of type Compare, and k1,
k2 of type Key. Similarly, an upper bounder
is a type UpperBounder such that
UpperBounderявляется предопределеннымKey.
Еслиupper(k1)и!comp(k1,k2), тоupper(k2),
for every upper of type UpperBounder,
comp of type Compare, and k1,
k2 of type Key.
[ORIG_END] -->
template<typename LowerBounder,typename UpperBounder>
std::pair<iterator,iterator> range(
LowerBounder lower,UpperBounder upper)const;
Requires:LowerBounder and UpperBounder are
a lower and upper bounder of key_compare, respectively. Effects: Returns a pair of iterators pointing to the beginning and one
past the end of the subsequence of elements satisfying lower and
upper simultaneously. If no such elements exist, the iterators
both point to the first element satisfying lower, or else
are equal to end() if this latter element does not exist. Complexity:O(log(n)). Variants: In place of lower or upper (or both),
the singular value boost::multi_index::unbounded can be
provided. This acts as a predicate which all values of type key_type
satisfy.
Индексы не могут быть сериализованы сами по себе, но только как часть<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, value_comp()
must be serialization-compatible with m.get<i>().value_comp(),
where i is the position of the ordered index in the container. Postconditions: On successful loading, each of the elements of
[begin(), end()) is a restored copy of the corresponding
element in [m.get<i>().begin(), m.get<i>().end()).
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 viceversa.
Статья Boost.MultiIndex Documentation - Ordered indices reference раздела Boost.MultiIndex Documentation - Reference может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.