#include<initializer_list>namespaceboost{namespacemulti_index{// sequenced index specifiertemplate<typenameTagList=tag<>>structsequenced;// 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
Последовательные индексы моделируются после семантики двунаправленного списка, такого как<std::list>. Элементы в секвенированном индексе по умолчанию отсортированы в соответствии с их порядком вставки: это означает, что новые элементы, вставленные через другой индекс<multi_index_container>, добавляются к концу секвенированного индекса. Кроме того, индекс позволяет свободно упорядочивать элементы в том же ключе, что и<std::list>. Достоверность итераторов и отсылок к элементам сохраняется во всех операциях.
За исключением случаев, когда отмечается или если соответствующий интерфейс не существует, секвенированные индексы проверяют те же требования к контейнеру, что и<std::list>: Мы лишь приводим описания тех видов и операций, которые либо не присутствуют в<std::list>, либо ведут себя иначе. Некоторые из наиболее важных различий:
¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
Вольт< [35] >, , , , , , , , , , , , , , , , , , , , , , . Это гибкая емантика, направленная на борьбу с ней< [35] >.
Сложность некоторых операций, в частности вставки и удаления, отличается от операцийstd::list.
В отличие отstd::list, вставки в секвенированный индекс могут потерпеть неудачу из-за столкновений с другими индексами. Это изменяет семантику операций, предусмотренных по отношению к их аналогам вstd::list.
Элементы в секвенированном индексе не являются изменчивыми и могут быть изменены только с помощью функцийreplaceиmodifyчленов.
[ORIG_END] -->
namespaceboost{namespacemulti_index{namespacedetail{template<implementation defined: dependent on types Value, Allocator, TagList>classname is implementation defined{public:// types:typedefValuevalue_type;typedefboost::tuples::null_typector_args;typedefTagListtag_list;typedefAllocatorallocator_type;typedeftypenameallocator_type::referencereference;typedeftypenameallocator_type::const_referenceconst_reference;typedefimplementation definediterator;typedefimplementation definedconst_iterator;typedefstd::size_tsize_type;typedefstd::ptrdiff_tdifference_type;typedeftypenameallocator_type::pointerpointer;typedeftypenameallocator_type::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);template<classInputIterator>voidassign(InputIteratorfirst,InputIteratorlast);voidassign(std::initializer_list<value_type>list);voidassign(size_typen,constvalue_type&value);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;voidresize(size_typen);voidresize(size_typen,constvalue_type&x);// access:const_referencefront()const;const_referenceback()const;// modifiers:template<typename...Args>std::pair<iterator,bool>emplace_front(Args&&...args);std::pair<iterator,bool>push_front(constvalue_type&x);std::pair<iterator,bool>push_front(value_type&&x);voidpop_front();template<typename...Args>std::pair<iterator,bool>emplace_back(Args&&...args);std::pair<iterator,bool>push_back(constvalue_type&x);std::pair<iterator,bool>push_back(value_type&&x);voidpop_back();template<typename...Args>std::pair<iterator,bool>emplace(iteratorposition,Args&&...args);std::pair<iterator,bool>insert(iteratorposition,constvalue_type&x);std::pair<iterator,bool>insert(iteratorposition,value_type&&x);voidinsert(iteratorposition,size_typen,constvalue_type&x);template<typenameInputIterator>voidinsert(iteratorposition,InputIteratorfirst,InputIteratorlast);voidinsert(iteratorposition,std::initializer_list<value_type>list);iteratorerase(iteratorposition);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);voidswap(index class name&x);voidclear()noexcept;// list operations:voidsplice(iteratorposition,index class name&x);voidsplice(iteratorposition,index class name&x,iteratori);voidsplice(iteratorposition,index class name&x,iteratorfirst,iteratorlast);voidremove(constvalue_type&value);template<typenamePredicate>voidremove_if(Predicatepred);voidunique();template<classBinaryPredicate>voidunique(BinaryPredicatebinary_pred);voidmerge(index class name&x);template<typenameCompare>voidmerge(index class name&x,Comparecomp);voidsort();template<typenameCompare>voidsort(Comparecomp);voidreverse()noexcept;// rearrange operations:voidrelocate(iteratorposition,iteratori);voidrelocate(iteratorposition,iteratorfirst,iteratorlast);template<typenameInputIterator>voidrearrange(InputIteratorfirst);}// 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
Здесь и в описаниях операций секвенированных индексов мы принимаем схему, изложенную в разделесигнатур сложности. Сигнатура сложности секвенированных индексов:
Последовательные индексы инстанцируются внутри<multi_index_container>и определяются с помощью<indexed_by>с<sequenced>указателя индекса. Обоснования зависят от следующих типов:
< [74] >< [75] >,
< [78] >< [79] >,
< [82] >[detapartio Slánda] (если не считать< [83] >].
<TagList>должен быть инстанциацией<tag>.Valueизmulti_index_container,
Allocatorизmulti_index_container,
TagListиз указателя индекса (при условии, что в противном случаеtag<>предполагается).
TagList must be an instantiation of
tag.
[ORIG_END] -->
Requires (first version):value_type is DefaultInsertable
into multi_index_container. Requires (second version):value_type is CopyInsertable
into multi_index_container. Effects: If size()<n, tries to append n-size() default-inserted
elements (first version) or copies of x (second version) at the end of
the index. If n<size(), erases the last size()-n elements. Note: If an expansion is requested, the size of the index is not guaranteed
to be n after this operation (other indices may ban insertions.)
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.
insert(begin(),x);// lvalue ref versioninsert(begin(),std::move(x));// rvalue ref version
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.
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.
insert(end(),x);// lvalue ref versioninsert(end(),std::move(x));// rvalue ref version
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.
Requires:value_type is EmplaceConstructible
into multi_index_container from args. Effects: Inserts a value_type object constructed with
std::forward<Args>(args)... before position if insertion
is allowed by all other indices of the 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 before position if insertion
is allowed by all other indices of the 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:position is a valid iterator of the index.
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 before position if insertion is allowed by all
other indices of the 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.
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 replacing is allowed by all other indices of the
multi_index_container. Postconditions: Validity of position is preserved
in all cases. 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 on sequenced
indices does not change the position of the element with respect to the index;
rearrangement on other indices may or might not succeed. If the rearrangement
fails, the element is erased. Postconditions: Validity of position is preserved if the
operation succeeds. 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 on sequenced
indices does not change the position of the element with respect to the index;
rearrangement on other indices may or might not succeed. 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. 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.
Последовательные индексы обеспечивают полный набор операций списка, найденных в<std::list>; однако семантика этих функций-членов отличается от семантики<std::list>в некоторых случаях, поскольку вставки могут не увенчаться успехом из-за запрета другими индексами. Аналогично, сложность операций может зависеть от других индексов, относящихся к тому же<multi_index_container>.
void splice(iterator position,index class name& x);
Requires:position is a valid iterator of the index.
&x!=this. Effects: Inserts the contents of x before position,
in the same order as they were in x. Those elements successfully
inserted are erased from x. Complexity:O(x.size()*I(n+x.size()) + x.size()*D(x.size())). Exception safety: Basic.
void splice(iterator position,index class name& x,iterator i);
Requires:position is a valid iterator of the index.
i is a valid dereferenceable iterator x. Effects: Inserts the element pointed to by i before
position: if insertion is successful, the element is erased from
x. In the special case &x==this, no copy or
deletion is performed, and the operation is always successful. If
position==i, no operation is performed. Postconditions: If &x==this, no iterator or reference
is invalidated. Complexity: If &x==this, constant; otherwise
O(I(n) + D(n)). Exception safety: If &x==this, nothrow;
otherwise, strong.
void splice(iterator position,index class name& x,iterator first,iterator last);
Requires:position is a valid iterator of the index.
first and last are valid iterators of x.
last is reachable from first. position
is not in the range [first,last). Effects: For each element in the range [first,last),
insertion is tried before position; if the operation is successful,
the element is erased from x. In the special case
&x==this, no copy or deletion is performed, and insertions are
always successful. Postconditions: If &x==this, no iterator or reference
is invalidated. Complexity: If &x==this, constant; otherwise
O(m*I(n+m) + m*D(x.size())) where m is the number
of elements in [first,last). Exception safety: If &x==this, nothrow;
otherwise, basic.
void remove(const value_type& value);
Effects: Erases all elements of the index which compare equal to
value. Complexity:O(n + m*D(n)), where m
is the number of elements erased. Exception safety: Basic.
Effects: Erases all elements x of the index for which
pred(x) holds. Complexity:O(n + m*D(n)), where m
is the number of elements erased. Exception safety: Basic.
void unique();
Effects: Eliminates all but the first element from every consecutive
group of equal elements referred to by the iterator i in the range
[first+1,last) for which *i==*(i-1). Complexity:O(n + m*D(n)), where m
is the number of elements erased. Exception safety: Basic.
Effects: Eliminates all but the first element from every consecutive
group of elements referred to by the iterator i in the range
[first+1,last) for which
binary_pred(*i,*(i-1)) holds. Complexity:O(n + m*D(n)), where m
is the number of elements erased. Exception safety: Basic.
void merge(index class name& x);
Requires:std::less<value_type> induces a
strict weak ordering over value_type.
Both the index and x are sorted according to
std::less<value_type>. Effects: Attempts to insert every element of x into the
corresponding position of the index (according to the order). Elements
successfully inserted are erased from x. The resulting sequence
is stable, i.e. equivalent elements of either container preserve their
relative position. In the special case &x==this, no operation
is performed. Postconditions: Elements in the index and remaining elements in
x are sorted.
Validity of iterators to the index and of non-erased elements of x
references is preserved. Complexity: If &x==this, constant; otherwise
O(n + x.size()*I(n+x.size()) + x.size()*D(x.size())). Exception safety: If &x==this, nothrow;
otherwise, basic.
template <typename Compare> void merge(index class name& x,Compare comp);
Requires:Compare induces a
strict weak ordering over value_type.
Both the index and x are sorted according to comp. Effects: Attempts to insert every element of x into the
corresponding position of the index (according to comp).
Elements successfully inserted are erased from x. The resulting
sequence is stable, i.e. equivalent elements of either container preserve
their relative position. In the special case &x==this, no
operation is performed. Postconditions: Elements in the index and remaining elements in
x are sorted according to comp.
Validity of iterators to the index and of non-erased elements of x
references is preserved. Complexity: If &x==this, constant; otherwise
O(n + x.size()*I(n+x.size()) + x.size()*D(x.size())). Exception safety: If &x==this, nothrow;
otherwise, basic.
void sort();
Requires:std::less<value_type> induces a
strict weark ordering over value_type. Effects: Sorts the index according to
std::less<value_type>. The sorting is stable, i.e.
equivalent elements preserve their relative position. Postconditions: Validity of iterators and references is preserved. Complexity:O(n*log(n)). Exception safety:nothrow if
std::less<value_type> does not throw; otherwise, basic.
Requires:Compare induces a
strict weak ordering over value_type. Effects: Sorts the index according to comp. The sorting
is stable, i.e. equivalent elements preserve their relative position. Postconditions: Validity of iterators and references is preserved. Complexity:O(n*log(n)). Exception safety:nothrow if comp does
not throw; otherwise, basic.
void reverse()noexcept;
Effects: Reverses the order of the elements in the index. Postconditions: Validity of iterators and references is preserved. Complexity:O(n).
Эти операции без аналога в<std::list>(хотя<splice>обеспечивает частично перекрывающуюся функциональность), выполняют индивидуальное и глобальное перепозиционирование элементов внутри индекса.
void relocate(iterator position,iterator i);
Requires:position is a valid iterator of the index.
i is a valid dereferenceable iterator of the index. Effects: Inserts the element pointed to by i before
position. If position==i, no operation is
performed. Postconditions: No iterator or reference is invalidated. Complexity: Constant. Exception safety:nothrow.
Requires:position is a valid iterator of the index.
first and last are valid iterators of the index.
last is reachable from first. position
is not in the range [first,last). Effects: The range of elements [first,last)
is repositioned just before position. Postconditions: No iterator or reference is invalidated. Complexity: Constant. Exception safety:nothrow.
Requires: The range [first,
std::advance(first,n)),
where n is the size of the index, is a
free view of the index. Effects: The elements are rearranged so as to match the
order of the previously described view. Postconditions: No iterator or reference is invalidated. Complexity:O(n). Exception safety: Basic.
Индексы не могут быть сериализованы сами по себе, а только как часть<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: No additional requirements to those imposed by 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()),
where i is the position of the sequenced index in the container.
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 - Sequenced indices reference раздела Boost.MultiIndex Documentation - Reference может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.