![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
Boost.MultiArray Reference ManualBoost , ,
|
<A > | Тип, который является моделью MultiArray |
<a,b > | Типовые объекты<A > |
<NumDims > | Числовой параметр, связанный с<A >. |
<Dims > | Некоторые числовые параметры, такие, что<0<Dims<NumDims >. |
<indices > | Объект, созданный некоторым количеством цепных вызовов<index_gen::operator[](index_range) >. |
<index_list > | An object whose type models Collection |
<idx > | Подписанное интегральное значение. |
<tmp > | Типовой объект<boost::array<index,NumDims> > |
Table 2. Associated Types
Type | Description |
---|---|
<value_type > | Это и есть тип контейнера. Если<NumDims == 1 >, то это<element >. В противном случае, это тип стоимости непосредственно вложенных контейнеров. |
<reference > | Это тип отсчета содержащегося значения. Если<NumDims == 1 >, то это<element& >. В остальном это тот же самый тип<template subarray<NumDims-1>::type >. |
<const_reference > |
This is the const reference type of the contained value.
If NumDims == 1 , then this is
const element& . Otherwise, this is the same
type as
template const_subarray<NumDims-1>::type . |
<size_type > | Это неподписанный интегральный тип. В основном используется для определения формы массива. |
difference_type | Это подписанный интегральный тип, используемый для представления расстояния между двумя итераторами. Такой же, как и<std::iterator_traits<iterator>::difference_type >. |
<iterator > |
This is an iterator over the values of A .
If NumDims == 1 , then it models
Random Access Iterator .
Otherwise it models
Random Access Traversal Iterator,
Readable Iterator,
Writable Iterator, and
Output Iterator . |
const_iterator | Это итератор константы над значениями<A >. |
<reverse_iterator > |
This is the reversed iterator, used to iterate backwards over the values of
A . |
const_reverse_iterator | Это обратный итератор.<A >. |
element |
This is the type of objects stored at the base of the
hierarchy of MultiArrays. It is the same as
template subarray<1>::value_type |
<index > | Это подписанный интегральный тип, используемый для индексации в<A >. Он также используется для представления шагов и индексных баз. |
index_gen | Этот тип используется для создания кортежа<index_range >, переданного<operator[] >для создания<array_view<Dims>::type >объекта. |
<index_range > | Этот тип определяет диапазон индексов по некоторому измерению MultiArray. Этот диапазон будет виден через объект<array_view<Dims>::type >. |
<template subarray<Dims>::type > | Это субмарина с размерами<Dims >. Это опорный тип<(NumDims - Dims) >размерности<A >, а также модели MultiArray. |
<template const_subarray<Dims>::type > | Это тип Const Subarray. |
template array_view<Dims>::type | Это вид с размерами<Dims >. Возвращается<operator[]( . Модель MultiArray. |
template
const_array_view<Dims>::type | Это вид конста с размерами<Dims >. |
Table 3. Valid Expressions
Expression | Return type | Semantics |
---|---|---|
<A::dimensionality > | <size_type > | Эта постоянная времени компиляции представляет собой число измерений массива (обратите внимание, что<A::dimensionality == NumDims >). |
<a.shape() > | <const size_type* > | Это возвращает список<NumDims >элементов, определяющих степень каждого размера массива. |
<a.strides() > | <const index* > | Это возвращает список<NumDims >элементов, определяющих шаг, связанный с каждым измерением массива. При доступе к значениям шаг используется для вычисления местоположения элемента в памяти. |
<a.index_bases() > | <const index* > | Это возвращает список<NumDims >элементов с указанием числового индекса первого элемента для каждого размера массива. |
<a.origin() > | element* if a is mutable,
const element* otherwise.
| Это возвращает адрес элемента, доступного выражению<a[0][0]...[0]. >. Если индексные базы положительны, этот элемент не будет существовать, но адрес все еще может быть использован для поиска действительного элемента с учетом его индексов. |
<a.num_dimensions() > | <size_type > | Это возвращает число измерений массива (обратите внимание, что<a.num_dimensions() == NumDims >). |
<a.num_elements() > | <size_type > | This returns the number of elements contained
in the array. It is equivalent to the following code:
std::accumulate(a.shape(),a.shape+a.num_dimensions(), size_type(1),std::multiplies<size_type>()); |
<a.size() > | <size_type > | Это возвращает число значений, содержащихся в<a >. Это эквивалентно<a.shape()[0]; >. |
<a(index_list) > | element& ; if a is mutable,
const element& otherwise.
|
This expression accesses a specific element of
a .index_list is the unique set
of indices that address the element returned. It is
equivalent to the following code (disregarding intermediate temporaries):
// multiply indices by strides std::transform(index_list.begin(), index_list.end(), a.strides(), tmp.begin(), std::multiplies<index>()), // add the sum of the products to the origin *std::accumulate(tmp.begin(), tmp.end(), a.origin()); |
<a.begin() > | iterator if a is mutable,
const_iterator otherwise.
| Это возвращает итератор, указывающий на начало<a >. |
<a.end() > | iterator if a is mutable,
const_iterator otherwise.
| Это возвращает итератор, указывающий на конец<a >. |
<a.rbegin() > | reverse_iterator if a is mutable,
const_reverse_iterator otherwise.
| Это возвращает обратный итератор, указывающий на начало<a >обратного. |
<a.rend() > | reverse_iterator if a is mutable,
const_reverse_iterator otherwise.
| Это возвращает обратный итератор, указывающий на конец<a >. |
<a[idx] > | reference if a is mutable,
const_reference otherwise.
| Это возвращает эталонный тип, который связан с значением индекса<idx ><a >. Обратите внимание, что если<i >является индексной базой для этого измерения, вышеупомянутое выражение возвращает<(idx-i) >элемент (счет с нуля). Это выражение эквивалентно<*(a.begin()+idx-a.index_bases()[0]); >. |
<a[indices] > | array_view<Dims>::type if
a is mutable,
const_array_view<Dims>::type otherwise.
|
This expression generates a view of the array determined by the
index_range and index values
used to construct indices . |
<a == b > | болтать | Это выполняет лексикографическое сравнение значений<a >и<b >. Тип элемента должен моделироватьРавенствоСравнимое, чтобы это выражение было действительным. |
<a < b > | болтать | Проводится лексикографическое сравнение значений<a >и<b >. Тип элемента должен моделироватьLessThanComparable, чтобы это выражение было действительным. |
<a <= b > | болтать | Это выполняет лексикографическое сравнение значений<a >и<b >. Тип элемента должен моделироватьEqualityComparableиLessThanComparable, чтобы это выражение было действительным. |
<a > b > | болтать | Это выполняет лексикографическое сравнение значений<a >и<b >. Тип элемента должен моделироватьEqualityComparableиLessThanComparable, чтобы это выражение было действительным. |
<a >= b > | болтать | Проводится лексикографическое сравнение значений<a >и<b >. Тип элемента должен моделироватьLessThanComparable, чтобы это выражение было действительным. |
begin()
and end()
execute in amortized
constant time.
size()
executes in at most linear time in the
MultiArray's size.
Table 4. Invariants
действительный диапазон | <[a.begin(),a.end()) >является действительным диапазоном. |
Размер диапазона | a.size() == std::distance(a.begin(),a.end()); . |
полнота | Итерация через диапазон<[a.begin(),a.end()) >будет проходить через каждый<value_type >из<a >. |
Эквивалентность аксессора |
Calling a[a1][a2]...[aN] where N==NumDims
yields the same result as calling
a(index_list) , where index_list
is a Collection containing the values a1...aN . |
Следующие типы, связанные с MultiArray, определяют интерфейс для создания просмотров существующих MultiArray. Их интерфейсы и роли в концепции описаны ниже.
<index_range
>объекты представляют собой полуоткрытые полосатые интервалы. Они объединяются (используя объект<index_gen
>) и передаются в MultiArray<operator[]
>для создания представления массива. При создании представления каждый<index_range
>обозначает диапазон действительных индексов вдоль одного измерения MultiArray. Элементы, которые доступны через набор диапазонов, будут включены в построенный вид. В некоторых случаях<index_range
>создается без указания начальных или конечных значений. В этих случаях объект интерпретируется как начинающийся в начале многолучевого измерения и заканчивающийся в его конце.
index_range
objects can be constructed and modified
several ways in order to allow convenient and clear expression of a
range of indices. To specify ranges, index_range
supports a set of constructors, mutating member functions, and a novel
specification involving inequality operators. Using inequality
operators, a half open range [5,10) can be specified as follows:
5 <= index_range() < 10;
или
4 < index_range() <= 9;
и так далее. Ниже приводится описание интерфейса<index_range
>.
Table 6. Associated Types
Type | Description |
---|---|
<index > | Это подписанный интегральный тип. Он используется для определения значений начала, окончания и шага. |
<size_type > | Это неподписанный интегральный тип. Он используется для сообщения о размере диапазона, который представляет<index_range >. |
Table 7. Valid Expressions
Expression | Return type | Semantics |
---|---|---|
<index_range(idx1,idx2,idx3) > | <index_range > | [idx1,idx2) idx3 . |
<index_range(idx1,idx2) > | <index_range > | Это создает<index_range >, представляющий интервал<[idx1,idx2) >с шагом единицы. Это эквивалентно<index_range(idx1,idx2,1) >. |
<index_range() > | <index_range > | Эта конструкция<index_range >с неопределенными значениями начала и окончания. |
<i.start(idx1) > | <index& > | При этом индекс старта составляет от<i >до<idx >. |
<i.finish(idx) > | <index& > | Этот показатель составляет от<i >до<idx >. |
<i.stride(idx) > | <index& > | idx . |
<i.start() > | <index > | Это возвращает стартовый индекс<i >. |
<i.finish() > | <index > | Это возвращает итоговый индекс<i >. |
<i.stride() > | <index > | Это возвращает длину шага<i >. |
<i.get_start(idx) > | <index > | Если<i >указывает начальное значение, это эквивалентно<i.start() >. В противном случае он вернется<idx >. |
<i.get_finish(idx) > | <index > | Если<i >указывает конечную величину, это эквивалентно<i.finish() >. В противном случае он вернется<idx >. |
<i.size(idx) > | <size_type > | Если<i >указывает как конечные, так и начальные значения, это эквивалентно<(i.finish()-i.start())/i.stride() >. В противном случае он возвращается<idx >. |
<i < idx > | <index > | Это еще один синтаксис для определения конечного значения. Это обозначение не включает<idx >в диапазон действительных индексов. Это эквивалентно<index_range(r.start(), idx, r.stride()) >. |
<i <= idx > | <index > | Это еще один синтаксис для определения конечного значения. Это обозначение включает<idx >в диапазон действительных индексов. Это эквивалентно<index_range(r.start(), idx + 1, r.stride()) >. |
<idx < i > | <index > | Это еще один синтаксис для определения начального значения. Это обозначение не включает<idx >в диапазон действительных индексов. Это эквивалентно<index_range(idx + 1, i.finish(), i.stride()) >. |
<idx <= i > | <index > | Это еще один синтаксис для определения начального значения. Это обозначение включает<idx1 >в диапазон действительных индексов. Это эквивалентно<index_range(idx, i.finish(), i.stride()) >. |
<i + idx > | <index > | Это выражение сдвигает начальные и конечные значения<i >на<idx >. Это эквивалентно<index_range(r.start()+idx1, r.finish()+idx, r.stride()) >. |
<i - idx > | <index > | Это выражение сдвигает начальные и конечные значения<i >на<idx >. Это эквивалентно<index_range(r.start()-idx1, r.finish()-idx, r.stride()) >. |
<index_gen
>агрегирует<index_range
>объекты с целью указания параметров просмотра. Цепные вызовы<operator[]
>хранят информацию о диапазоне и измерении, используемую для создания нового представления в MultiArray.
Table 8. Notation
<Dims,Ranges > | Неподписанные интегральные ценности. |
<x > | Объект типа<template gen_type<Dims,Ranges>::type >. |
<i > | Объект типа<index_range >. |
<idx > | Объекты типа<index >. |
Table 9. Associated Types
Type | Description |
---|---|
<index > | Это подписанный интегральный тип. Используется для определения дегенеративных размеров. |
<size_type > | Это неподписанный интегральный тип. Он используется для сообщения о размере диапазона, который представляет<index_range >. |
template gen_type::<Dims,Ranges>::type | Генератор этого типа называет результат<Dims >цепных вызовов<index_gen::operator[] >. Параметр<Ranges >определяется числом указанных дегенеративных диапазонов (т.е. вызовов к<operator[](index) >). Обратите внимание, что<index_gen >и<gen_type<0,0>::type >являются одинаковыми. |
Table 10. Valid Expressions
Expression | Return type | Semantics |
---|---|---|
<index_gen() > | <gen_type<0,0>::type > | Построен объект<index_gen >. Затем этот объект может быть использован для генерации наборов значений<index_range >. |
<x[i] > | gen_type<Dims+1,Ranges+1>::type | Возвращает новый объект, содержащий все предыдущие<index_range >объекты в дополнение к<i. >Цепные призывы к<operator[] >являются средством, с помощью которого<index_range >объекты агрегируются. |
<x[idx] > | gen_type<Dims,Ranges+1>::type | Возвращает новый объект, содержащий все предыдущие<index_range >объекты в дополнение к вырожденному диапазону,<index_range(idx,idx). >Обратите внимание, что это НЕ эквивалентно<x[index_range(idx,idx)]. >, который возвращает объект типа<gen_type<Dims+1,Ranges+1>::type >. |
Повышаю. MultiArray определяет класс массива<multi_array
>и два класса адаптера<multi_array_ref
>и<const_multi_array_ref
>. Три класса модели MultiArray и поэтому они имеют много функций.<multi_array_ref
>отличается от<multi_array
>тем, что<multi_array
>управляет собственной памятью, в то время как<multi_array_ref
>проходит блок памяти, которым он ожидает управлять извне.<const_multi_array_ref
>отличается от<multi_array_ref
>тем, что базовые элементы, которые он адаптирует, не могут быть изменены через его интерфейс, хотя некоторые свойства массива, включая форму массива и базы индексов, могут быть изменены. Функциональность, которую имеют классы, описана ниже.
Note: Preconditions, Effects, and Implementation. Throughout the following sections, small pieces of C++ code are used to specify constraints such as preconditions, effects, and postconditions. These do not necessarily describe the underlying implementation of array components; rather, they describe the expected input to and behavior of the specified operations. Failure to meet preconditions results in undefined behavior. Not all effects (i.e. copy constructors, etc.) must be mimicked exactly. The code snippets for effects intend to capture the essence of the described operation.
Queries.
element* data(); const element* data() const;
Это возвращает указатель к началу смежного блока, который содержит данные массива. Если все размеры массива 0-индексированы и хранятся в порядке возрастания, это эквивалентно<origin()
>. Обратите внимание, что<const_multi_array_ref
>предоставляет только конст-версию этой функции.
element* origin(); const element* origin() const;
Это возвращает исходный элемент<multi_array
>. Обратите внимание, что<const_multi_array_ref
>предоставляет только конст-версию этой функции. (перенаправлено с «MultiArray»)
const index* index_bases();
Это возвращает индексные базы для<multi_array
>. (перенаправлено с «MultiArray»)
const index* strides();
Это возвращает успехи<multi_array
>. (перенаправлено с «MultiArray»)
const size_type* shape();
Это возвращает форму<multi_array
>. (перенаправлено с «MultiArray»)
Comparators.
bool operator==(const *array-type*& rhs); bool operator!=(const *array-type*& rhs); bool operator<(const *array-type*& rhs); bool operator>(const *array-type*& rhs); bool operator>=(const *array-type*& rhs); bool operator<=(const *array-type*& rhs);
Каждый компаратор выполняет лексикографическое сравнение по типам значений двух массивов. (перенаправлено с «MultiArray»)
Preconditions. element
must support the
comparator corresponding to that called on
multi_array
.
Complexity. O(num_elements()
).
Modifiers.
template <typename SizeList> void reshape(const SizeList& sizes)
Это меняет форму<multi_array
>. Число элементов и индексные базы остаются неизменными, но число значений на каждом уровне вложенной иерархии контейнеров может меняться.
SizeList
Requirements. SizeList
must model
Collection.
Preconditions.
std::accumulate(sizes.begin(),sizes.end(),size_type(1),std::times<size_type>()) == this->num_elements(); sizes.size() == NumDims;
Postconditions. std::equal(sizes.begin(),sizes.end(),this->shape) == true;
template <typename BaseList> void reindex(const BaseList& values);
Это изменяет индексные базы<multi_array
>, чтобы соответствовать значениям в<values
>.
BaseList
Requirements. BaseList
must model
Collection.
Preconditions. values.size() == NumDims;
Postconditions. std::equal(values.begin(),values.end(),this->index_bases());
void reindex(index value);
Это изменяет индексные базы всех измерений<multi_array
>до<value
>.
Postconditions.
std::count_if(this->index_bases(),this->index_bases()+this->num_dimensions(), std::bind_2nd(std::equal_to<index>(),value)) == this->num_dimensions();
multi_array
is a multi-dimensional container that
supports random access iteration. Its number of dimensions is
fixed at compile time, but its shape and the number of elements it
contains are specified during its construction. The number of elements
will remain fixed for the duration of a
multi_array
's lifetime, but the shape of the container can
be changed. A multi_array
manages its data elements
using a replaceable allocator.
Model Of. MultiArray, CopyConstructible. Depending on the element type, it may also model EqualityComparable and LessThanComparable.
Synopsis.
namespace boost { template <typename ValueType, std::size_t NumDims, typename Allocator = std::allocator<ValueType> > class multi_array { public: // types: typedef ValueType element; typedef *unspecified* value_type; typedef *unspecified* reference; typedef *unspecified* const_reference; typedef *unspecified* difference_type; typedef *unspecified* iterator; typedef *unspecified* const_iterator; typedef *unspecified* reverse_iterator; typedef *unspecified* const_reverse_iterator; typedef multi_array_types::size_type size_type; typedef multi_array_types::index index; typedef multi_array_types::index_gen index_gen; typedef multi_array_types::index_range index_range; typedef multi_array_types::extent_gen extent_gen; typedef multi_array_types::extent_range extent_range; typedef *unspecified* storage_order_type; // template typedefs template <std::size_t Dims> struct subarray; template <std::size_t Dims> struct const_subarray; template <std::size_t Dims> struct array_view; template <std::size_t Dims> struct const_array_view; static const std::size_t dimensionality = NumDims; // constructors and destructors multi_array(); template <typename ExtentList> explicit multi_array(const ExtentList& sizes, const storage_order_type& store = c_storage_order(), const Allocator& alloc = Allocator()); explicit multi_array(const extents_tuple& ranges, const storage_order_type& store = c_storage_order(), const Allocator& alloc = Allocator()); multi_array(const multi_array& x); multi_array(const const_multi_array_ref<ValueType,NumDims>& x); multi_array(const const_subarray<NumDims>::type& x); multi_array(const const_array_view<NumDims>::type& x); multi_array(const multi_array_ref<ValueType,NumDims>& x); multi_array(const subarray<NumDims>::type& x); multi_array(const array_view<NumDims>::type& x); ~multi_array(); // modifiers multi_array& operator=(const multi_array& x); template <class Array> multi_array& operator=(const Array& x); // iterators: iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; reverse_iterator rbegin(); reverse_iterator rend(); const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; // capacity: size_type size() const; size_type num_elements() const; size_type num_dimensions() const; // element access: template <typename IndexList> element& operator()(const IndexList& indices); template <typename IndexList> const element& operator()(const IndexList& indices) const; reference operator[](index i); const_reference operator[](index i) const; array_view<Dims>::type operator[](const indices_tuple& r); const_array_view<Dims>::type operator[](const indices_tuple& r) const; // queries element* data(); const element* data() const; element* origin(); const element* origin() const; const size_type* shape() const; const index* strides() const; const index* index_bases() const; const storage_order_type& storage_order() const; // comparators bool operator==(const multi_array& rhs); bool operator!=(const multi_array& rhs); bool operator<(const multi_array& rhs); bool operator>(const multi_array& rhs); bool operator>=(const multi_array& rhs); bool operator<=(const multi_array& rhs); // modifiers: template <typename InputIterator> void assign(InputIterator begin, InputIterator end); template <typename SizeList> void reshape(const SizeList& sizes) template <typename BaseList> void reindex(const BaseList& values); void reindex(index value); template <typename ExtentList> multi_array& resize(const ExtentList& extents); multi_array& resize(extents_tuple& extents); };
Constructors.
template <typename ExtentList> explicit multi_array(const ExtentList& sizes, const storage_order_type& store = c_storage_order(), const Allocator& alloc = Allocator());
Это позволяет построить<multi_array
>с использованием заданных параметров.<sizes
>определяет форму построенного<multi_array
>.<store
>определяет порядок хранения или компоновку в памяти размеров массива.<alloc
>используется для выделения содержащихся элементов.
ExtentList
Requirements. ExtentList
must model Collection.
Preconditions. sizes.size() == NumDims;
explicit multi_array(extent_gen::gen_type<NumDims>::type ranges, const storage_order_type& store = c_storage_order(), const Allocator& alloc = Allocator());
Это позволяет построить<multi_array
>с использованием заданных параметров.<ranges
>определяет форму и индексные основания построенного мультимассивного массива. Это результат<NumDims
>цепных вызовов<extent_gen::operator[]
>.<store
>определяет порядок хранения или компоновку в памяти размеров массива.<alloc
>является распределителем, используемым для выделения памяти, используемой для хранения<multi_array
>элементов.
multi_array(const multi_array& x); multi_array(const const_multi_array_ref<ValueType,NumDims>& x); multi_array(const const_subarray<NumDims>::type& x); multi_array(const const_array_view<NumDims>::type& x); multi_array(const multi_array_ref<ValueType,NumDims>& x); multi_array(const subarray<NumDims>::type& x); multi_array(const array_view<NumDims>::type& x);
Все эти конструкторы строят<multi_array
>и выполняют глубокую копию<x
>.
Complexity. This performs O(x.num_elements()
) calls to
element
's copy
constructor.
multi_array();
Это конструирует<multi_array
>, форма которого (0, ...,0) и не содержит элементов.
Note on Constructors.
The multi_array
construction expressions,
multi_array<int,3> A(boost::extents[5][4][3]);
and
boost::array<multi_array_base::index,3> my_extents = {{5, 4, 3}}; multi_array<int,3> A(my_extents);
are equivalent.
Modifiers.
multi_array& operator=(const multi_array& x); template <class Array> multi_array& operator=(const Array& x);
Это выполняет элементную копию<x
>в ток<multi_array
>.
Array
Requirements. Array
must model MultiArray.
Preconditions.
std::equal(this->shape(),this->shape()+this->num_dimensions(), x.shape());
Postconditions.
(*.this) == x;
Complexity. The assignment operators perform
O(x.num_elements()
) calls to element
's
copy constructor.
template <typename InputIterator> void assign(InputIterator begin, InputIterator end);
Это копирует элементы в диапазоне<[begin,end)
>в массив. Это эквивалентно<std::copy(begin,end,this->data())
>.
Preconditions. std::distance(begin,end) == this->num_elements();
Complexity.
The assign
member function performs
O(this->num_elements()
) calls to
ValueType
's copy constructor.
multi_array& resize(extent_gen::gen_type<NumDims>::type extents); template <typename ExtentList> multi_array& resize(const ExtentList& extents);
Эта функция изменяет размер массива до формы, указанной в<extents
>, которая является либо сгенерированным списком степеней, либо моделью концепции<Collection
>. Содержимое массива сохраняется, когда это возможно; если новый размер массива меньше, то некоторые данные будут потеряны. Любые новые элементы, созданные путем изменения размера массива, инициализируются с помощью конструктора по умолчанию<element
>.
Queries.
storage_order_type& storage_order() const;
Этот запрос возвращает объект заказа хранения, связанный с<multi_array
>. Его можно использовать для создания нового массива с тем же порядком хранения.
multi_array_ref
is a multi-dimensional container
adaptor. It provides the MultiArray interface over any contiguous
block of elements. multi_array_ref
exports the
same interface as multi_array
, with the exception
of the constructors.
Model Of. multi_array_ref
models
MultiArray,
CopyConstructible.
and depending on the element type, it may also model
EqualityComparable and LessThanComparable.
Detailed descriptions are provided here only for operations that are
not described in the multi_array
reference.
Synopsis.
namespace boost { template <typename ValueType, std::size_t NumDims> class multi_array_ref { public: // types: typedef ValueType element; typedef *unspecified* value_type; typedef *unspecified* reference; typedef *unspecified* const_reference; typedef *unspecified* difference_type; typedef *unspecified* iterator; typedef *unspecified* const_iterator; typedef *unspecified* reverse_iterator; typedef *unspecified* const_reverse_iterator; typedef multi_array_types::size_type size_type; typedef multi_array_types::index index; typedef multi_array_types::index_gen index_gen; typedef multi_array_types::index_range index_range; typedef multi_array_types::extent_gen extent_gen; typedef multi_array_types::extent_range extent_range; typedef *unspecified* storage_order_type; // template typedefs template <std::size_t Dims> struct subarray; template <std::size_t Dims> struct const_subarray; template <std::size_t Dims> struct array_view; template <std::size_t Dims> struct const_array_view; static const std::size_t dimensionality = NumDims; // constructors and destructors template <typename ExtentList> explicit multi_array_ref(element* data, const ExtentList& sizes, const storage_order_type& store = c_storage_order()); explicit multi_array_ref(element* data, const extents_tuple& ranges, const storage_order_type& store = c_storage_order()); multi_array_ref(const multi_array_ref& x); ~multi_array_ref(); // modifiers multi_array_ref& operator=(const multi_array_ref& x); template <class Array> multi_array_ref& operator=(const Array& x); // iterators: iterator begin(); iterator end(); const_iterator begin() const; const_iterator end() const; reverse_iterator rbegin(); reverse_iterator rend(); const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; // capacity: size_type size() const; size_type num_elements() const; size_type num_dimensions() const; // element access: template <typename IndexList> element& operator()(const IndexList& indices); template <typename IndexList> const element& operator()(const IndexList& indices) const; reference operator[](index i); const_reference operator[](index i) const; array_view<Dims>::type operator[](const indices_tuple& r); const_array_view<Dims>::type operator[](const indices_tuple& r) const; // queries element* data(); const element* data() const; element* origin(); const element* origin() const; const size_type* shape() const; const index* strides() const; const index* index_bases() const; const storage_order_type& storage_order() const; // comparators bool operator==(const multi_array_ref& rhs); bool operator!=(const multi_array_ref& rhs); bool operator<(const multi_array_ref& rhs); bool operator>(const multi_array_ref& rhs); bool operator>=(const multi_array_ref& rhs); bool operator<=(const multi_array_ref& rhs); // modifiers: template <typename InputIterator> void assign(InputIterator begin, InputIterator end); template <typename SizeList> void reshape(const SizeList& sizes) template <typename BaseList> void reindex(const BaseList& values); void reindex(index value); };
Constructors.
template <typename ExtentList> explicit multi_array_ref(element* data, const ExtentList& sizes, const storage_order& store = c_storage_order(), const Allocator& alloc = Allocator());
Это позволяет построить<multi_array_ref
>с использованием заданных параметров.<sizes
>определяет форму построенного<multi_array_ref
>.<store
>определяет порядок хранения или компоновку в памяти размеров массива.<alloc
>используется для выделения содержащихся элементов.
ExtentList
Requirements. ExtentList
must model Collection.
Preconditions. sizes.size() == NumDims;
explicit multi_array_ref(element* data, extent_gen::gen_type<NumDims>::type ranges, const storage_order& store = c_storage_order());
Это создает<multi_array_ref
>с использованием заданных параметров.<ranges
>определяет форму и индексные основания построенного мульти-мультипликатора. Он является результатом<NumDims
>цепных вызовов<extent_gen::operator[]
>.<store
>определяет порядок хранения или компоновку в памяти размеров массива.
multi_array_ref(const multi_array_ref& x);
Это неглубокая копия<x
>.
Complexity. Constant time (for contrast, compare this to
the multi_array
class copy constructor.
Modifiers.
multi_array_ref& operator=(const multi_array_ref& x); template <class Array> multi_array_ref& operator=(const Array& x);
Это выполняет элементную копию<x
>в ток<multi_array_ref
>.
Array
Requirements. Array
must model MultiArray.
Preconditions.
std::equal(this->shape(),this->shape()+this->num_dimensions(), x.shape());
Postconditions.
(*.this) == x;
Complexity. The assignment operators perform
O(x.num_elements()
) calls to element
's
copy constructor.
const_multi_array_ref
is a multi-dimensional container
adaptor. It provides the MultiArray interface over any contiguous
block of elements. const_multi_array_ref
exports the
same interface as multi_array
, with the exception
of the constructors.
Model Of. const_multi_array_ref
models
MultiArray,
CopyConstructible.
and depending on the element type, it may also model
EqualityComparable and LessThanComparable.
Detailed descriptions are provided here only for operations that are
not described in the multi_array
reference.
Synopsis.
namespace boost { template <typename ValueType, std::size_t NumDims, typename TPtr = const T*> class const_multi_array_ref { public: // types: typedef ValueType element; typedef *unspecified* value_type; typedef *unspecified* reference; typedef *unspecified* const_reference; typedef *unspecified* difference_type; typedef *unspecified* iterator; typedef *unspecified* const_iterator; typedef *unspecified* reverse_iterator; typedef *unspecified* const_reverse_iterator; typedef multi_array_types::size_type size_type; typedef multi_array_types::index index; typedef multi_array_types::index_gen index_gen; typedef multi_array_types::index_range index_range; typedef multi_array_types::extent_gen extent_gen; typedef multi_array_types::extent_range extent_range; typedef *unspecified* storage_order_type; // template typedefs template <std::size_t Dims> struct subarray; template <std::size_t Dims> struct const_subarray; template <std::size_t Dims> struct array_view; template <std::size_t Dims> struct const_array_view; // structors template <typename ExtentList> explicit const_multi_array_ref(TPtr data, const ExtentList& sizes, const storage_order_type& store = c_storage_order()); explicit const_multi_array_ref(TPtr data, const extents_tuple& ranges, const storage_order_type& store = c_storage_order()); const_multi_array_ref(const const_multi_array_ref& x); ~const_multi_array_ref(); // iterators: const_iterator begin() const; const_iterator end() const; const_reverse_iterator rbegin() const; const_reverse_iterator rend() const; // capacity: size_type size() const; size_type num_elements() const; size_type num_dimensions() const; // element access: template <typename IndexList> const element& operator()(const IndexList& indices) const; const_reference operator[](index i) const; const_array_view<Dims>::type operator[](const indices_tuple& r) const; // queries const element* data() const; const element* origin() const; const size_type* shape() const; const index* strides() const; const index* index_bases() const; const storage_order_type& storage_order() const; // comparators bool operator==(const const_multi_array_ref& rhs); bool operator!=(const const_multi_array_ref& rhs); bool operator<(const const_multi_array_ref& rhs); bool operator>(const const_multi_array_ref& rhs); bool operator>=(const const_multi_array_ref& rhs); bool operator<=(const const_multi_array_ref& rhs); // modifiers: template <typename SizeList> void reshape(const SizeList& sizes) template <typename BaseList> void reindex(const BaseList& values); void reindex(index value); };
Constructors.
template <typename ExtentList> explicit const_multi_array_ref(TPtr data, const ExtentList& sizes, const storage_order& store = c_storage_order());
Это создает<const_multi_array_ref
>с использованием заданных параметров.<sizes
>определяет форму построенного<const_multi_array_ref
>.<store
>определяет порядок хранения или компоновку в памяти размеров массива.
ExtentList
Requirements. ExtentList
must model Collection.
Preconditions. sizes.size() == NumDims;
explicit const_multi_array_ref(TPtr data, extent_gen::gen_type<NumDims>::type ranges, const storage_order& store = c_storage_order());
Effects.
This constructs a const_multi_array_ref
using the specified
parameters. ranges
specifies the shape and
index bases of the constructed const_multi_array_ref. It is the result of
NumDims
chained calls to
extent_gen::operator[]
. store
specifies the storage order or layout in memory of the array
dimensions.
const_multi_array_ref(const const_multi_array_ref& x);
Effects. Это неглубокая копия<x
>.
namespace multi_array_types { typedef *unspecified* index; typedef *unspecified* size_type; typedef *unspecified* difference_type; typedef *unspecified* index_range; typedef *unspecified* extent_range; typedef *unspecified* index_gen; typedef *unspecified* extent_gen; }
Пространство имен<multi_array_types
>определяет типы, связанные с<multi_array
>,<multi_array_ref
>и<const_multi_array_ref
>, которые не зависят от параметров шаблона. Эти типы находят общее применение со всеми. Многомерные компоненты. Они определены в пространстве имен, из которого они могут быть легко доступны. За исключением<extent_gen
>и<extent_range
>, эти типы выполняют роли одного и того же имени, требуемые MultiArray, и описаны в его определении понятия.<extent_gen
>и<extent_range
>описаны ниже.
<extent_range
>объекты определяют полуоткрытые интервалы. Они предоставляют информацию о форме и индексе для конструкторов<multi_array
>,<multi_array_ref
>и<const_multi_array_ref
>.<extent_range
>s передаются в совокупности конструктору массива (см.<extent_gen
>для более подробной информации).
Synopsis.
class extent_range { public: typedef multi_array_types::index index; typedef multi_array_types::size_type size_type; // Structors extent_range(index start, index finish); extent_range(index finish); ~extent_range(); // Queries index start(); index finish(); size_type size(); };
Model Of. DefaultConstructible,CopyConstructible
Methods and Types.
extent_range(index start, index finish)
Этот конструктор определяет полуоткрытый интервал<[start,finish)
>. Выражение<finish
>должно быть больше<start
>.
extent_range(index finish)
Этот конструктор определяет полуоткрытый интервал<[0,finish)
>. Значение<finish
>должно быть положительным.
index start()
Эта функция возвращает первый индекс, представленный диапазоном.
index finish()
Эта функция возвращает верхнее граничное значение полуоткрытого интервала. Обратите внимание, что диапазон не включает это значение.
size_type size()
Эта функция возвращает размер указанного диапазона. Это эквивалентно<finish()-start()
>.
Класс<extent_gen
>определяет интерфейс для агрегирования формы массива и индексации информации, передаваемой конструктору<multi_array
>,<multi_array_ref
>или<const_multi_array_ref
>. Его интерфейс имитирует синтаксис, используемый для объявления встроенных типов массивов в C++. Например, в то время как 3-мерный массив<int
>значений в C++ будет объявлен как:
int A[3][4][5],
Аналогичный<multi_array
>будет объявлен:
multi_array<int,3> A(extents[3][4][5]).
Synopsis.
template <std::size_t NumRanges> class *implementation_defined* { public: typedef multi_array_types::index index; typedef multi_array_types::size_type size_type; template <std::size_t NumRanges> class gen_type; gen_type<NumRanges+1>::type operator[](const range& a_range) const; gen_type<NumRanges+1>::type operator[](index idx) const; }; typedef *implementation_defined*<0> extent_gen;
Methods and Types.
template gen_type<Ranges>::type
Генератор этого типа используется для указания результата<Ranges
>цепных вызовов<extent_gen::operator[].
>. Они<extent_gen
>и<gen_type<0>::type
>одинаковы.
gen_type<NumRanges+1>::type
operator[](const extent_range& a_range) const;
Эта функция возвращает новый объект, содержащий все предыдущие<extent_range
>объекты в дополнение к<a_range.
><extent_range
>объектам, агрегированным цепными вызовами к<operator[]
>.
gen_type<NumRanges+1>::type
operator[](index idx) const;
Эта функция возвращает новый объект, содержащий все предыдущие<extent_range
>объекты в дополнение к<extent_range(0,idx).
>. Эта функция дает конструкторам массивов аналогичный синтаксис традиционной многомерной декларации массива C.
Для синтаксического удобства Boost.MultiArray определяет два глобальных объекта как часть своего интерфейса. Эти объекты играют роль генераторов объектов; вовлекающие их выражения создают другие объекты, представляющие интерес.
При некоторых обстоятельствах два глобальных объекта могут считаться чрезмерными накладными расходами. Их конструкцию можно предотвратить, определив символ препроцессора<BOOST_MULTI_ARRAY_NO_GENERATORS
>перед включением<boost/multi_array.hpp.
>.
namespace boost { multi_array_base::extent_gen extents; }
Повышаю. Классы массивов MultiArray используют глобальный объект<extents
>для определения формы массива во время их строительства. Например, 3 на 3 на 3<multi_array
>построено следующим образом:
multi_array<int,3> A(extents[3][3][3]);
Тот же массив может быть создан путем явного объявления объекта<extent_gen
>локально, но глобальный объект делает эту декларацию ненужной.
namespace boost { multi_array_base::index_gen indices; }
Концепция MultiArray определяет связанный тип<index_gen
>, который используется для создания просмотров.<indices
>является глобальным объектом, который выполняет роль<index_gen
>для всех компонентов массива, предоставляемых этой библиотекой, и связанных с ними подкатегории и представления.
Например, при использовании объекта<indices
>вид массива<A
>сконструирован следующим образом:
A[indices[index_range(0,5)][2][index_range(2,4)]];
Повышаю. MultiArray предоставляет классы признаков<subarray_gen
>,<const_subarray_gen
>,<array_view_gen
>и<const_array_view_gen
>для именования типов, связанных с массивом, в шаблонах функций. В целом это не более удобно для использования, чем генераторы вложенного типа, но автор библиотеки обнаружил, что некоторые компиляторы C++ неправильно обрабатывают шаблоны, вложенные в типы параметров шаблона функции. Эти генераторы представляют собой обходной путь для этого дефицита. Следующий фрагмент кода иллюстрирует соответствие между классом признаков<array_view_gen
>и типом<array_view
>, связанным с массивом:
template <typename Array> void my_function() { typedef typename Array::template array_view<3>::type view1_t; typedef typename boost::array_view_gen<Array,3>::type view2_t; // ... }
В приведенном выше примере<view1_t
>и<view2_t
>имеют один и тот же тип.
В то время как многомерный массив представляет собой иерархию контейнеров элементов, в какой-то момент элементы должны быть выложены в память. В результате один многомерный массив может быть представлен в памяти более чем одним способом.
Например, рассмотрим двухмерный массив, показанный ниже в матричных обозначениях:
Вот как вышеупомянутый массив выражается в C++:
int a[3][4] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
Это пример хранения строк, где элементы каждой строки хранятся сопряжённо. В то время как C++ прозрачно обрабатывает доступ к элементам массива, вы также можете управлять массивом и его индексацией вручную. Один из способов выразить это в памяти заключается в следующем:
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; int s[] = { 4, 1 };
С последней декларацией<a
>и шагами<s
>к элементу<a(i,j)
>массива можно получить доступ с помощью выражения
*a+i*s[0]+j*s[1]
.
Один и тот же двухмерный массив может быть выложен колонкой следующим образом:
int a[] = { 0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11 }; int s[] = { 3, 1 };
Обратите внимание, что здесь шаги разные. В результате выражение, приведенное выше для значений доступа, будет работать с этой парой данных.
В дополнение к порядку размерности также можно хранить любое измерение в порядке убывания. Например, возвращаясь к первому примеру, первое измерение примерного массива, строки, могут быть сохранены в обратном порядке, в результате чего:
int data[] = { 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3 }; int *a = data + 8; int s[] = { -4, 1 };
Обратите внимание, что в этом примере<a
>должно быть явно установлено происхождение. В предыдущих примерах первым элементом, хранящимся в памяти, было происхождение; здесь это уже не так.
В качестве альтернативы, второе измерение или столбцы могут быть обращены вспять, и строки хранятся в порядке возрастания:
int data[] = { 3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8 }; int *a = data + 3; int s[] = { 4, -1 };
Наконец, оба измерения могут храниться в порядке убывания:
int data[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; int *a = data + 11; int s[] = { -4, -1 };
All of the above arrays are equivalent. The expression
given above for a(i,j)
will yield the same value
regardless of the memory layout.
Boost.MultiArray arrays can be created with customized storage
parameters as described above. Thus, existing data can be adapted
(with multi_array_ref
илиconst_multi_array_ref
) as suited to the array
abstraction. A common usage of this feature would be to wrap arrays
that must interoperate with Fortran routines so they can be
manipulated naturally at both the C++ and Fortran levels. The
following sections describe the Boost.MultiArray components used to
specify memory layout.
class c_storage_order { c_storage_order(); };
<c_storage_order
>используется для указания того, что массив должен хранить свои элементы, используя ту же компоновку, что и примитивные многомерные массивы C++, то есть от последнего измерения до первого. Это порядок хранения по умолчанию для массивов, предоставляемых этой библиотекой.
class fortran_storage_order { fortran_storage_order(); };
<fortran_storage_order
>используется для указания того, что массив должен хранить свои элементы, используя ту же компоновку памяти, что и многомерный массив Fortran, то есть от первого измерения до последнего.
template <std::size_t NumDims> class general_storage_order { template <typename OrderingIter, typename AscendingIter> general_storage_order(OrderingIter ordering, AscendingIter ascending); };
<general_storage_order
>позволяет пользователю задать произвольный макет памяти для содержимого массива. Построенный объект передается конструктору массива для того, чтобы указать порядок хранения.
OrderingIter
and AscendingIter
must model the InputIterator
concept. Both
iterators must refer to a range of NumDims
elements. AscendingIter
points to objects
convertible to bool
. A value of
true
means that a dimension is stored in ascending
order while false
means that a dimension is stored
in descending order. OrderingIter
specifies the
order in which dimensions are stored.
По умолчанию методы доступа к массиву<operator()
>и<operator[]
>выполняют проверку диапазона. Если поставляемый индекс находится вне диапазона, определенного для массива, утверждение прервет программу. Чтобы отключить проверку диапазона (по причинам производительности в производственных выпусках), определите макрос препроцессора<BOOST_DISABLE_ASSERTS
>до включения multi_array.hpp в приложение.
Статья Boost.MultiArray Reference Manual раздела может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.
:: Главная :: ::
реклама |