Карта сайта Kansoftware
НОВОСТИУСЛУГИРЕШЕНИЯКОНТАКТЫ
Разработка программного обеспечения

Boost.MultiIndex Documentation - Ordered indices reference

Boost , , Boost.MultiIndex Documentation - Reference

Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Boost.MultiIndex Ordered indices reference



Contents

Header "boost/multi_index/ordered_index_fwd.hpp" synopsis

namespace boost{
namespace multi_index{
// index specifiers ordered_unique and ordered_non_unique
template<consult ordered_unique reference for arguments>
struct ordered_unique;
template<consult ordered_non_unique reference for arguments>
struct ordered_non_unique;
// indices
namespace detail{
template<implementation defined> class index name is implementation defined;
} // namespace boost::multi_index::detail
} // namespace boost::multi_index 
} // namespace boost

<ordered_index_fwd.hpp>представляет форвардные декларации для указателей индексов<ordered_unique>и<ordered_non_unique>и связанные с нимиупорядоченные индексыклассов.

Header "boost/multi_index/ordered_index.hpp" synopsis

#include <initializer_list>
namespace boost{
namespace multi_index{
// index specifiers ordered_unique and ordered_non_unique
template<consult ordered_unique reference for arguments>
struct ordered_unique;
template<consult ordered_non_unique reference for arguments>
struct ordered_non_unique;
// indices
namespace detail{
template<implementation defined> class index class name implementation defined;
// index comparison:
// OP is any of ==,<,!=,>,>=,<=
template<arg set 1,arg set 2>
bool operator OP(
  const index class name<arg set 1>& x,const index class name<arg set 2>& y);
// index specialized algorithms:
template<implementation defined>
void swap(index class name& x,index class name& y);
} // namespace boost::multi_index::detail
} // namespace boost::multi_index 
} // namespace boost

Index specifiers ordered_unique and ordered_non_unique

Этиуказатели индексовпозволяют вставлятьупорядоченные индексыбез и с учетом дублирующих элементов, соответственно. Синтаксис<ordered_unique>и<ordered_non_unique>совпадают, поэтому мы описываем их сгруппированным образом.<ordered_unique>и<ordered_non_unique>могут быть представлены в двух различных формах, в зависимости от того, предоставляется ли список тегов для индекса:

template<
  typename KeyFromValue,
  typename Compare=std::less<KeyFromValue::result_type>
>
struct (ordered_unique | ordered_non_unique);
template<
  typename TagList,
  typename KeyFromValue,
  typename Compare=std::less<KeyFromValue::result_type>
>
struct (ordered_unique | ordered_non_unique);

Если это так, то<TagList>должно быть преобразовано в<tag>. Аргументы шаблона используются соответствующей реализацией индекса, ссылаясь на раздел ссылкиупорядоченных индексовдля дальнейших объяснений их приемлемых значений типа.

Ordered indices

Упорядоченный индекс обеспечивает заданный интерфейс к основной куче элементов, содержащихся в<multi_index_container>. Упорядоченный индекс конкретизируется согласно заданному<Key Extractor>, который извлекает ключи из элементов<multi_index_container>и сравнительного предиката.

Существует два варианта упорядоченных индексов:уникальный, не допускающий дублирования элементов (по отношению к связанному с ним сравнительному предикату) инеуникальный, принимающий эти дубликаты. Интерфейс этих двух вариантов одинаков, поэтому они документируются вместе с небольшими различиями, явно выраженными при их существовании.

За исключением случаев, когда отмечен или если соответствующий интерфейс не существует, упорядоченные индексы (как уникальные, так и неуникальные) удовлетворяют требованиям C++ для ассоциативных контейнеров по адресу[associative.reqmts].(поддержка уникальных и эквивалентных ключей, соответственно). Соответственно сохраняется валидность итераторов и ссылок на элементы. Мы предоставляем только описания тех типов и операций, которые не соответствуют или не соответствуют стандартным требованиям.

namespace boost{
namespace multi_index{
implementation defined unbounded; // see range()
namespace detail{
template<implementation defined: dependent on types Value, Allocator,
  TagList, KeyFromValue, Compare>
class name is implementation defined
{ 
public:
  // types:
  typedef typename KeyFromValue::result_type         key_type;
  typedef Value                                      value_type;
  typedef KeyFromValue                               key_from_value;
  typedef Compare                                    key_compare;
  typedef implementation defined                     value_compare;
  typedef boost::tuple<key_from_value,key_compare>   ctor_args;
  typedef TagList                                    tag_list;
  typedef Allocator                                  allocator_type;
  typedef typename Allocator::reference              reference;
  typedef typename Allocator::const_reference        const_reference;
  typedef implementation defined                     iterator;
  typedef implementation defined                     const_iterator;
  typedef implementation defined                     size_type;      
  typedef implementation defined                     difference_type;
  typedef typename Allocator::pointer                pointer;
  typedef typename Allocator::const_pointer          const_pointer;
  typedef equivalent to
    std::reverse_iterator<iterator>                  reverse_iterator;
  typedef equivalent to
    std::reverse_iterator<const_iterator>            const_reverse_iterator;
  // construct/copy/destroy:
  index class name& operator=(const index class name& x);
  index class name& operator=(std::initializer_list<value_type> list);
  allocator_type get_allocator()const noexcept;
  // iterators:
  iterator               begin()noexcept;
  const_iterator         begin()const noexcept;
  iterator               end()noexcept;
  const_iterator         end()const noexcept;
  reverse_iterator       rbegin()noexcept;
  const_reverse_iterator rbegin()const noexcept;
  reverse_iterator       rend()noexcept;
  const_reverse_iterator rend()const noexcept;
  const_iterator         cbegin()const noexcept;
  const_iterator         cend()const noexcept;
  const_reverse_iterator crbegin()const noexcept;
  const_reverse_iterator crend()const noexcept;
 
  iterator       iterator_to(const value_type& x);
  const_iterator iterator_to(const value_type& x)const;
  // capacity:
  bool      empty()const noexcept;
  size_type size()const noexcept;
  size_type max_size()const noexcept;
  // modifiers:
  template<typename... Args>
  std::pair<iterator,bool> emplace(Args&&... args);
  template <typename... Args>
  iterator emplace_hint(iterator position,Args&&... args);
  std::pair<iterator,bool> insert(const value_type& x);
  std::pair<iterator,bool> insert(value_type&& x);
  iterator insert(iterator position,const value_type& x);
  iterator insert(iterator position,value_type&& x);
  template<typename InputIterator>
  void insert(InputIterator first,InputIterator last);
  void insert(std::initializer_list<value_type> list);
  iterator  erase(iterator position);
  size_type erase(const key_type& x);
  iterator  erase(iterator first,iterator last);
  bool replace(iterator position,const value_type& x);
  bool replace(iterator position,value_type&& x);
  template<typename Modifier> bool modify(iterator position,Modifier mod);
  template<typename Modifier,typename Rollback>
  bool modify(iterator position,Modifier mod,Rollback back);
  template<typename Modifier> bool modify_key(iterator position,Modifier mod);
  template<typename Modifier,typename Rollback>
  bool modify_key(iterator position,Modifier mod,Rollback back);
  
  void swap(index class name& x);
  void clear()noexcept;
  // observers:
  key_from_value key_extractor()const;
  key_compare    key_comp()const;
  value_compare  value_comp()const;
  // set operations:
  template<typename CompatibleKey>
  iterator find(const CompatibleKey& x)const;
  template<typename CompatibleKey,typename CompatibleCompare>
  iterator find(
    const CompatibleKey& x,const CompatibleCompare& comp)const;
  template<typename CompatibleKey>
  size_type count(const CompatibleKey& x)const;
  template<typename CompatibleKey,typename CompatibleCompare>
  size_type count(const CompatibleKey& x,const CompatibleCompare& comp)const;
  template<typename CompatibleKey>
  iterator lower_bound(const CompatibleKey& x)const;
  template<typename CompatibleKey,typename CompatibleCompare>
  iterator lower_bound(
    const CompatibleKey& x,const CompatibleCompare& comp)const;
  template<typename CompatibleKey>
  iterator upper_bound(const CompatibleKey& x)const;
  template<typename CompatibleKey,typename CompatibleCompare>
  iterator upper_bound(
    const CompatibleKey& x,const CompatibleCompare& comp)const;
  template<typename CompatibleKey>
  std::pair<iterator,iterator> equal_range(
    const CompatibleKey& x)const;
  template<typename CompatibleKey,typename CompatibleCompare>
  std::pair<iterator,iterator> equal_range(
    const CompatibleKey& x,const CompatibleCompare& comp)const;
  // range:
  template<typename LowerBounder,typename UpperBounder>
  std::pair<iterator,iterator> range(
    LowerBounder lower,UpperBounder upper)const;
};
// index comparison:
template<arg set 1,arg set 2>
bool operator==(
  const index class name<arg set 1>& x,
  const index class name<arg set 2>& y)
{
  return x.size()==y.size()&&std::equal(x.begin(),x.end(),y.begin());
}
template<arg set 1,arg set 2>
bool operator<(
  const index class name<arg set 1>& x,
  const index class name<arg set 2>& y)
{
  return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end());
}
template<arg set 1,arg set 2>
bool operator!=(
  const index class name<arg set 1>& x,
  const index class name<arg set 2>& y)
{
  return !(x==y);
}
template<arg set 1,arg set 2>
bool operator>(
  const index class name<arg set 1>& x,
  const index class name<arg set 2>& y)
{
  return y<x;
}
template<arg set 1,arg set 2>
bool operator>=(
  const index class name<arg set 1>& x,
  const index class name<arg set 2>& y)
{
  return !(x<y);
}
template<arg set 1,arg set 2>
bool operator<=(
  const index class name<arg set 1>& x,
  const index class name<arg set 2>& y)
{
  return !(x>y);
}
// index specialized algorithms:
template<implementation defined>
void swap(index class name& x,index class name& y);
} // namespace boost::multi_index::detail
} // namespace boost::multi_index 
} // namespace boost

Complexity signature

Здесь и в описаниях операций упорядоченных индексов мы принимаем схему, изложенную в разделеподписи сложности. Сигнатурой сложности упорядоченных индексов является:

  • < [34] >,
  • < [36] >,
  • челночный< [38] >(постоянный),< [38] >,< [39] >,< [39] >,< [38] >,< [38] >,< [38] >,< [38] >,< [39] >,< [38] >,< [38] >,< [38] >,< [39] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [39] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >,< [38] >.
  • < [42] >[править править код]
  • < [44] >< [44] >< [44] >< [45] >< [45] >< [45] >< [45] >< [45] >< [45] >< [45] >< [45] >.
  • < [48] >[< [48] >] [< [48] >] [< [48] >] [< [48] >]] [< [49] >]] [[< [49] >]]] [[< [49] >]] [[< [49] >]]]] [[< [48] >]] [[< [48] >]]] [[[< [49] >]]]] [[[[]]]]] [[[[]]]]] [[[[]]]]] [[[[]]]]]] [[[[]]]]] [[[[]]]]] [[[[]]]]]] [[[[]]]]]] [[[[]]]]] [[[[]]]]]] [[[[]]]]]] [[[[]]]]]] [[[[]]]]] [[[[]]]]]] [[[[]]]]] [[[[]]]]] [[[[]]]]]] [[[[]]]]] [[[]]]]
Копирование:c(n)=n*log(n),
  • вставка:i(n)=log(n),
  • h(n)=1(постоянно), если элемент подсказки находится сразу после точки вставки,h(n)=log(n)в противном случае,
  • Удаление:d(n)=1(амортизированная постоянная),
  • r(n)=1(постоянно), если положение элемента не изменяется,r(n)=log(n)в противном случае,
  • m(n)=1(постоянно), если положение элемента не изменяется,m(n)=log(n)в противном случае.
  • [ORIG_END] -->

    Instantiation types

    Упорядоченные индексы инстанцируются внутри<multi_index_container>и определяются с помощью<indexed_by>суказателями индексов<ordered_unique>и<ordered_non_unique>.. Обоснования зависят от следующих типов:

    • < [61] >< [62] >,
    • < [65] >< [66] >,
    • < [69] >,< [69] >,< [69] >,< [69] >, [< [70] >], [], [].
    • < [73] >Северо-Западный,
    • < [75] >Щедрость тела.
    <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] -->

    Constructors, copy and assignment

    Как поясняется в разделеконцептов индексов, индексы не имеют публичных конструкторов или деструкторов. Присвоение, с другой стороны, предусмотрено.

    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.

    Iterators

    iterator       iterator_to(const value_type& x);
    const_iterator iterator_to(const value_type& x)const;
    Requires: x is a reference to an element of the container.
    Returns: An iterator to x.
    Complexity: Constant.
    Exception safety: nothrow.

    Modifiers

    template<typename... Args>
    std::pair<iterator,bool> emplace(Args&&... args);
    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.
    template<typename... Args>
    iterator emplace_hint(iterator position, Args&&... args);
    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.
    std::pair<iterator,bool> insert(const value_type& x);
    std::pair<iterator,bool> insert(value_type&& x);
    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.
    iterator insert(iterator position,const value_type& x);
    iterator insert(iterator position,value_type&& x);
    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.
    template<typename InputIterator>
    void insert(InputIterator first,InputIterator last);
    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.
    void insert(std::initializer_list<value_type> list);
    Effects:
    insert(list.begin(),list.end());
    
    iterator erase(iterator position);
    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.
    bool replace(iterator position,const value_type& x);
    bool replace(iterator position,value_type&& x);
    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.
    template<typename Modifier> bool modify(iterator position,Modifier mod);
    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.
    template<typename Modifier,typename Rollback>
    bool modify(iterator position,Modifier mod,Rollback back);
    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.
    template<typename Modifier> bool modify_key(iterator position,Modifier mod);
    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.
    template<typename Modifier,typename Rollback>
    bool modify_key(iterator position,Modifier mod,Rollback back);
    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.

    Observers

    Помимо стандартных<key_comp>и<value_comp>, упорядоченные индексы имеют функцию члена для извлечения используемого внутреннего экстрактора ключа.

    key_from_value key_extractor()const;
    Returns a copy of the key_from_value object used to construct the index.
    Complexity: Constant.

    Set operations

    Упорядоченные индексы обеспечивают полную функциональность поиска, требуемую[associative.reqmts], а именно<find>,<count>,<lower_bound>,<upper_bound>и<equal_range>. Кроме того, эти функции членов шаблонизированы, чтобы обеспечить нестандартные аргументы, таким образом расширяя типы разрешенных поисковых операций. Вид аргументов, допустимых при вызове функций поиска, определяется следующей концепцией.

    Рассмотрим двоичный предикат<Compare>, индуцирующий строгий слабый порядок над значениями типа<Key>. Пара типов [<CompatibleKey>,<CompatibleCompare>] называетсясовместимым расширением<Compare>, если

    1. < [94] >[< [94] >] [< [95] >]< [96] >< [94] >] [< [94] >] [< [95] >] [< [95] >] [< [94] >]]
    2. < [102] >,< [103] >,< [102] >,< [102] >,< [103] >,
    3. < [106] >,< [107] >
    4. ,< [108] >,
    5. < [113] >
    6. ,< [114] >
    для каждого<c_comp>типа<CompatibleCompare>,<comp>типа<Compare>,<ck>типа<CompatibleKey>и<k1>,<k2>типа<Key>.CompatibleCompare— двоичный предикат надKey,CompatibleKey,
  • CompatibleCompare— двоичный предикат надCompatibleKey,Key,
  • Еслиc_comp(ck,k1), то!c_comp(k1,ck)
  • Если!c_comp(ck,k1)и!comp(k1,k2), то!c_comp(ck,k2)
  • Если!c_comp(k1,ck)и!comp(k2,k1), то!c_comp(k2,ck)
  • 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()>.

    В контексте совместимого расширения или совместимого ключа выражения «эквивалент», «меньше чем» и «больше чем» принимают свои очевидные интерпретации.

    template<typename CompatibleKey> iterator find(const CompatibleKey& x)const;
    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)).
    template<typename CompatibleKey,typename CompatibleCompare>
    iterator find(const CompatibleKey& x,const CompatibleCompare& comp)const;
    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)).
    template<typename CompatibleKey> size_type
    count(const CompatibleKey& x)const;
    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)).
    template<typename CompatibleKey,typename CompatibleCompare>
    size_type count(const CompatibleKey& x,const CompatibleCompare& comp)const;
    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)).
    template<typename CompatibleKey>
    iterator lower_bound(const CompatibleKey& x)const;
    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)).
    template<typename CompatibleKey,typename CompatibleCompare>
    iterator lower_bound(const CompatibleKey& x,const CompatibleCompare& comp)const;
    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)).
    template<typename CompatibleKey>
    iterator upper_bound(const CompatibleKey& x)const;
    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)).
    template<typename CompatibleKey,typename CompatibleCompare>
    iterator upper_bound(const CompatibleKey& x,const CompatibleCompare& comp)const;
    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)).
    template<typename CompatibleKey>
    std::pair<iterator,iterator> equal_range(
      const CompatibleKey& x)const;
    Requires: CompatibleKey is a compatible key of key_compare.
    Effects: Equivalent to make_pair(lower_bound(x),upper_bound(x)).
    Complexity: O(log(n)).
    template<typename CompatibleKey,typename CompatibleCompare>
    std::pair<iterator,iterator> equal_range(
      const CompatibleKey& x,const CompatibleCompare& comp)const;
    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 operations

    Функция члена<range>не определена для сортированных ассоциативных контейнеров, но упорядоченные индексы обеспечивают ее как удобную утилиту. Диапазон или интервал определяется двумя условиями для нижней и верхней границ, которые моделируются после следующих понятий.

    Рассмотрим двоичный предикат<Compare>, индуцирующий строгий слабый порядок над значениями типа<Key>. Тип<LowerBounder>называетсянижним граничником<Compare>, если

    1. < [132] >[< [133] >] [< [132] >] [< [133] >]
    2. < [136] >и< [137] >,< [138] >,
    для каждого<lower>типа<LowerBounder>,<comp>типа<Compare>и<k1>,<k2>типа<Key>. Точно так жеверхняя границаявляется типом<UpperBounder>таким, что
    1. < [142] >< [143] >< [143] >< [142] >< [143] >< [143] >
    2. < [146] >и< [147] >,< [148] >,
    для каждого<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
    1. UpperBounderявляется предопределеннымKey.
    2. Если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.

    Serialization

    Индексы не могут быть сериализованы сами по себе, но только как часть<multi_index_container>, в которую они встроены. При описании дополнительных предварительных условий и гарантий, связанных с упорядоченными индексами в отношении сериализации их встраиваемых контейнеров, мы используем понятия, определенные в<multi_index_container>.Раздел сериализации.

    Operation: saving of a multi_index_container m to an output archive (XML archive) ar.
    Requires: No additional requirements to those imposed by the container.
    Operation: loading of a multi_index_container m' 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_iterator it 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_iterator it' 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.



    Пересмотрено 26 ноября 2015 года

    © Copyright 2003-2015 Joaquín M López Muñoz. Распространяется под лицензией Boost Software License, версия 1.0. (См. сопроводительный файлLICENSE_1_0.txtили копию на) http://www.boost.org/LICENSE_1_0.txt

    Статья Boost.MultiIndex Documentation - Ordered indices reference раздела Boost.MultiIndex Documentation - Reference может быть полезна для разработчиков на c++ и boost.




    Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.



    :: Главная :: Boost.MultiIndex Documentation - Reference ::


    реклама


    ©KANSoftWare (разработка программного обеспечения, создание программ, создание интерактивных сайтов), 2007
    Top.Mail.Ru

    Время компиляции файла: 2024-08-30 11:47:00
    2025-05-20 08:21:12/0.010962963104248/0