namespaceboost{namespacemulti_index{// index specifiers ranked_unique and ranked_non_uniquetemplate<consult ranked_unique reference for arguments>structranked_unique;template<consult ranked_non_unique reference for arguments>structranked_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 ranked_unique and ranked_non_uniquetemplate<consult ranked_unique reference for arguments>structranked_unique;template<consult ranked_non_unique reference for arguments>structranked_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
Эти указатели индексов позволяют вставлять рейтинговые индексы без и с учетом дублирующих элементов, соответственно. Синтаксис ranked_unique и ranked_non_unique совпадают, поэтому мы описываем их сгруппированным образом. ranked_unique и ranked_non_unique могут быть представлены в двух различных формах, в зависимости от того, предоставляется ли список тегов для индекса:
При наличии TagList должен представлять собой инстанциацию шаблона класса tag. Аргументы шаблона используются соответствующей реализацией индекса, см. раздел ссылки ранжированных индексов для дальнейших объяснений их приемлемых значений типа.
Ранжированные индексы представляют собой вариацию упорядоченных индексов, обеспечивающую дополнительные возможности для расчета и доступа по рангу; ранг элемента - расстояние до него от начала индекса. Помимо этого расширения ранжированные индексы воспроизводят публичный интерфейс упорядоченных индексов с разницей, сложностью, что удаление выполняется в логарифмическом, а не в постоянном времени. Кроме того, ожидается, что время выполнения и потребление памяти будут хуже из-за внутренней бухгалтерской отчетности, необходимой для поддержания информации, связанной с рангом. Как и упорядоченные индексы, ранжированные индексы могут быть уникальными (не допускаются дублирующие элементы) или неуникальными: любая версия связана с другим указателем индекса, но интерфейс обоих типов индексов одинаков.
Ниже мы описываем только дополнительные операции, предоставляемые ранжированными индексами: для остальных ссылаемся на документацию для упорядоченных индексов, имея в виду случайные различия в сложности.
namespaceboost{namespacemulti_index{implementation defined unbounded;// see range_rank()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;// rank operations:iteratornth(size_typen)const;size_typerank(iteratorposition)const;template<typenameCompatibleKey>size_typefind_rank(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>size_typefind_rank(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>size_typelower_bound_rank(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>size_typelower_bound_rank(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>size_typeupper_bound_rank(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>size_typeupper_bound_rank(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameCompatibleKey>std::pair<size_type,size_type>equal_range_rank(constCompatibleKey&x)const;template<typenameCompatibleKey,typenameCompatibleCompare>std::pair<size_type,size_type>equal_range_rank(constCompatibleKey&x,constCompatibleCompare&comp)const;template<typenameLowerBounder,typenameUpperBounder>std::pair<size_type,size_type>range_rank(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
Мы следуем терминологии, описанной в разделе сложность подписи . Сигнатура сложности ранжированных индексов:
Приступ:c(n)=n*log(n),
i(n)=log(n),
h(n)=log(n) в противном случае,
d(n)=log(n),
r(n)=1[править]
m(n)=1 (постоянно), если положение элемента не изменяется, m(n)=log(n) в противном случае.
Копирование:c(n)=n*log(n),
вставка:i(n)=log(n),
h(n)=1(постоянно), если элемент подсказки находится сразу после точки вставки,h(n)=log(n)в противном случае,
d(n)=log(n),
замена:r(n)=1(постоянная), если положение элемента не изменяется,r(n)=log(n)в противном случае,
m(n)=1(постоянно), если положение элемента не изменяется,m(n)=log(n)в противном случае.
[ORIG_END] -->
Эти гарантии сложности такие же, как у упорядоченных индексов. За исключением удаления, которое является log(n) здесь и амортизированной постоянной там.
ранг итератора it заданного контейнера c (и, в более широком смысле, элемента, на который он указывает, если итератор является сносным) является std::distance(c.begin(),it).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Equivalent to rank(find(x,comp)). Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Equivalent to rank(lower_bound(x,comp)). Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Equivalent to rank(upper_bound(x,comp)). Complexity:O(log(n)).
Requires:CompatibleKey is a compatible key of
key_compare. Effects: Equivalent to make_pair(lower_bound_rank(x),upper_bound_rank(x)). Complexity:O(log(n)).
Requires: (CompatibleKey, CompatibleCompare)
is a compatible extension of key_compare. Effects: Equivalent to
make_pair(lower_bound_rank(x,comp),upper_bound_rank(x,comp)). Complexity:O(log(n)).
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.
Статья Boost.MultiIndex Documentation - Ranked indices reference раздела Boost.MultiIndex Documentation - Reference может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.