//! \addtogroup Containers //! \{ //! \file pideque.h //! \brief //! \~english Declares \a PIDeque //! \~russian Объявление \a PIDeque //! \~\authors //! \~english //! Ivan Pelipenko peri4ko@yandex.ru; //! Andrey Bychkov work.a.b@yandex.ru; //! \~russian //! Иван Пелипенко peri4ko@yandex.ru; //! Андрей Бычков work.a.b@yandex.ru; //! \~\} /* PIP - Platform Independent Primitives Dynamic array of any type Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef PIDEQUE_H #define PIDEQUE_H #include "picontainers.h" //! \addtogroup Containers //! \{ //! \class PIDeque //! \brief //! \~english Sequence two-way linear container - dynamic size array of any type. //! \~russian Последовательный двухсторонний контейнер с линейной памятью - динамический массив любого типа. //! \~\} //! \details //! \~english //! The elements are stored contiguously, //! which means that elements can be accessed not only through iterators, //! but also using offsets to regular pointers to elements. //! This means that a pointer to an element of a PIDeque may be passed to any function //! that expects a pointer to an element of an array. //! To add elements you can use functions \a append() and \a insert(), //! to remove elements you can use functions \a remove() and \a removeOne(), \a removeWhere(). //! Change size by function \a resize() and \a assign(). //! Items in an array are numbered, starting from zero. //! This number is called the item's index. //! So the first item has index 0, the last has index `size() - 1`. //! A set of various convenient functions is also available for the array, //! for example: \a indexOf(), \a contains(), \a entries(), \a isEmpty(), \a isNotEmpty(), //! \a every(), \a any(), \a forEach(), \a indexWhere(), \a getRange(), \a sort(), //! \a map(), \a reduce(), \a filter(), \a flatten(), \a reshape() and others. //! //! The storage of the PIDeque is handled automatically, //! being expanded as needed. //! PIDeque usually occupy more space than \a PIVector, //! because more memory is allocated to handle future growth //! from both the beginning and the end. //! This way a PIDeque does not need to reallocate each time an element is inserted, //! but only when the additional memory is exhausted. //! The total amount of allocated memory can be queried using \a capacity() function. //! Reallocations are usually costly operations in terms of performance. //! The \a reserve() function can be used to eliminate reallocations //! if the number of elements is known beforehand. //! //! The complexity (efficiency) of common operations on PIDeque is as follows: //! - Random access - constant 𝓞(1) //! - Insertion or removal of elements at the end or begin - amortized constant 𝓞(1) //! - Insertion or removal of elements - linear in the distance to the end of the array 𝓞(n) //! //! \~russian //! Элементы хранятся непрерывно, а значит доступны не только через итераторы, //! но и с помощью смещений для обычных указателей на элементы. //! Это означает, что указатель на элемент PIDeque может передаваться в любую функцию, //! ожидающую указатель на элемент массива. //! Добавить элементы можно с помощью функции \a append() или \a insert(), //! а удалить с помощью \a remove() или \a removeOne(), \a removeWhere(). //! Изменить размер можно функцией \a resize() или \a assign(). //! Массив индексируется с нуля: //! первый элемент массива имеет индекс, равный `0`, //! а индекс последнего элемента равен `size() - 1`. //! Также для массива доступен набор различных удобных функций, //! например: \a indexOf, \a contains(), \a entries(), \a isEmpty(), \a isNotEmpty(), //! \a every(), \a any(), \a forEach(), \a indexWhere(), \a getRange(), \a sort(), //! \a map(), \a reduce(), \a filter(), \a flatten(), \a reshape() и другие. //! //! Память PIDeque обрабатывается автоматически, //! расширяясь по мере необходимости. //! PIDeque занимает больше места, чем \a PIVector, поскольку //! больше памяти выделяется для обработки будущего роста и с начала и с конца. //! Таким образом, память для PIDeque требуется выделять //! не при каждой вставке элемента, а только после исчерпания дополнительной памяти. //! Общий объём выделенной памяти можно получить с помощью функции \a capacity(). //! //! Выделение памяти обычно является дорогостоящей операцией //! с точки зрения производительности. //! Функцию \a reserve() можно использовать для исключения выделения памяти, //! если количество элементов известно заранее. //! //! Сложность (эффективность) обычных операций над PIDeque следующая: //! - Произвольный доступ — постоянная 𝓞(1) //! - Вставка и удаление элементов в конце или начале — амортизированная постоянная 𝓞(1) //! - Вставка и удаление элементов — линейная по расстоянию до конца массива 𝓞(n) //! //! \~\sa \a PIVector, \a PIMap template class PIDeque { public: typedef bool (*CompareFunc)(const T & , const T & ); typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; //! \~english Constructs an empty array. //! \~russian Создает пустой массив. inline PIDeque(): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) } //! \~english Copy constructor. //! \~russian Копирующий конструктор. inline PIDeque(const PIDeque & other): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) alloc_forward(other.pid_size); newT(pid_data + pid_start, other.pid_data + other.pid_start, pid_size); } //! \~english Contructs array from //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). //! \~russian Создает массив из //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). //! \~\details //! \~\code //! PIDeque v{1,2,3}; //! piCout << v; // {1, 2, 3} //! \endcode inline PIDeque(std::initializer_list init_list): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) alloc_forward(init_list.size()); newT(pid_data, init_list.begin(), init_list.size()); } //! \~english Contructs array from raw `data`. //! This constructor reserve `size` and copy from `data` pointer. //! \~russian Создает массив из указателя на данные `data` и размер `size`. //! То есть выделяет память для `size` элементов и копирует данные из указателя `data`. inline PIDeque(const T * data, size_t size): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) alloc_forward(size); newT(pid_data + pid_start, data, pid_size); } //! \~english Contructs array with size `size` filled elements `e`. //! \~russian Создает массив из `size` элементов заполненных `e`. inline PIDeque(size_t pid_size, const T & e = T()): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) resize(pid_size, e); } //! \~english Contructs array with size `size` and elements created by function `f(size_t i)`. //! \~russian Создает массив из `size` элементов созданных функцией `f(size_t i)`. //! \~\details //! \~english Can use //! [Lambda expressions](https://en.cppreference.com/w/cpp/language/lambda) //! as constructor argument. //! \~russian Позволяет передавать //! [Лямбда-выражения](https://ru.cppreference.com/w/cpp/language/lambda) //! для создания элементов в конструкторе. //! \~\code //! PIDeque v(5, [](size_t i){return i*2;}); //! piCout << v; // {0, 2, 4, 6, 8} //! \endcode inline PIDeque(size_t piv_size, std::function f): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) resize(piv_size, f); } //! \~english Move constructor. //! \~russian Перемещающий конструктор. inline PIDeque(PIDeque && other): pid_data(other.pid_data), pid_size(other.pid_size), pid_rsize(other.pid_rsize), pid_start(other.pid_start) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) other._reset(); } inline virtual ~PIDeque() { PIINTROSPECTION_CONTAINER_DELETE(T) PIINTROSPECTION_CONTAINER_FREE(T, (pid_rsize)) deleteT(pid_data + pid_start, pid_size); dealloc(); _reset(); } //! \~english Assign operator. //! \~russian Оператор присваивания. inline PIDeque & operator =(const PIDeque & other) { if (this == &other) return *this; deleteT(pid_data + pid_start, pid_size); alloc_forward(other.pid_size); newT(pid_data + pid_start, other.pid_data + other.pid_start, pid_size); return *this; } //! \~english Assign move operator. //! \~russian Оператор перемещающего присваивания. inline PIDeque & operator =(PIDeque && other) { swap(other); return *this; } class iterator { friend class PIDeque; private: inline iterator(PIDeque * v, ssize_t p): parent(v), pos(p) {} PIDeque * parent; ssize_t pos; public: typedef T value_type; typedef T* pointer; typedef T& reference; typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; inline iterator(): parent(0), pos(0) {} inline T & operator *() {return (*parent)[pos];} inline const T & operator *() const {return (*parent)[pos];} inline T & operator ->() {return (*parent)[pos];} inline const T & operator ->() const {return (*parent)[pos];} inline iterator & operator ++() { ++pos; return *this; } inline iterator operator ++(int) { auto tmp = *this; ++*this; return tmp; } inline iterator & operator --() { --pos; return *this; } inline iterator operator --(int) { auto tmp = *this; --*this; return tmp; } inline iterator & operator +=(const iterator & it) { pos += it.pos; return *this; } inline iterator & operator +=(size_t p) { pos += p; return *this; } inline iterator & operator -=(const iterator & it) { pos -= it.pos; return *this; } inline iterator & operator -=(size_t p) { pos -= p; return *this; } friend inline iterator operator -(size_t p, const iterator & it) {return it - p;} friend inline iterator operator -(const iterator & it, size_t p) { auto tmp = it; tmp -= p; return tmp; } friend inline std::ptrdiff_t operator -(const iterator & it1, const iterator & it2) { return it1.pos - it2.pos; } friend inline iterator operator +(size_t p, const iterator & it) {return it + p;} friend inline iterator operator +(const iterator & it, size_t p) { auto tmp = it; tmp += p; return tmp; } inline bool operator ==(const iterator & it) const {return (pos == it.pos);} inline bool operator !=(const iterator & it) const {return (pos != it.pos);} friend inline bool operator <(const iterator & it1, const iterator & it2) { return it1.pos < it2.pos; } friend inline bool operator <=(const iterator & it1, const iterator & it2) { return it1.pos <= it2.pos; } friend inline bool operator >(const iterator & it1, const iterator & it2) { return it1.pos > it2.pos; } friend inline bool operator >=(const iterator & it1, const iterator & it2) { return it1.pos >= it2.pos; } }; class const_iterator { friend class PIDeque; private: inline const_iterator(const PIDeque * v, ssize_t p): parent(v), pos(p) {} const PIDeque * parent; ssize_t pos; public: typedef T value_type; typedef T* pointer; typedef T& reference; typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; inline const_iterator(): parent(0), pos(0) {} inline const T & operator *() const {return (*parent)[pos];} inline const T & operator ->() const {return (*parent)[pos];} inline const_iterator & operator ++() { ++pos; return *this; } inline const_iterator operator ++(int) { auto tmp = *this; ++*this; return tmp; } inline const_iterator & operator --() { --pos; return *this; } inline const_iterator operator --(int) { auto tmp = *this; --*this; return tmp; } inline const_iterator & operator +=(const const_iterator & it) { pos += it.pos; return *this; } inline const_iterator & operator +=(size_t p) { pos += p; return *this; } inline const_iterator & operator -=(const const_iterator & it) { pos -= it.pos; return *this; } inline const_iterator & operator -=(size_t p) { pos -= p; return *this; } friend inline const_iterator operator -(size_t p, const const_iterator & it) {return it - p;} friend inline const_iterator operator -(const const_iterator & it, size_t p) { auto tmp = it; tmp -= p; return tmp; } friend inline std::ptrdiff_t operator -(const const_iterator & it1, const const_iterator & it2) { return it1.pos - it2.pos; } friend inline const_iterator operator +(size_t p, const const_iterator & it) {return it + p;} friend inline const_iterator operator +(const const_iterator & it, size_t p) { auto tmp = it; tmp += p; return tmp; } inline bool operator ==(const const_iterator & it) const {return (pos == it.pos);} inline bool operator !=(const const_iterator & it) const {return (pos != it.pos);} friend inline bool operator <(const const_iterator & it1, const const_iterator & it2) { return it1.pos < it2.pos; } friend inline bool operator <=(const const_iterator & it1, const const_iterator & it2) { return it1.pos <= it2.pos; } friend inline bool operator >(const const_iterator & it1, const const_iterator & it2) { return it1.pos > it2.pos; } friend inline bool operator >=(const const_iterator & it1, const const_iterator & it2) { return it1.pos >= it2.pos; } }; class reverse_iterator { friend class PIDeque; private: inline reverse_iterator(PIDeque * v, ssize_t p): parent(v), pos(p) {} PIDeque * parent; ssize_t pos; public: typedef T value_type; typedef T* pointer; typedef T& reference; typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; inline reverse_iterator(): parent(0), pos(0) {} inline T & operator *() {return (*parent)[pos];} inline const T & operator *() const {return (*parent)[pos];} inline T & operator ->() {return (*parent)[pos];} inline const T & operator ->() const {return (*parent)[pos];} inline reverse_iterator & operator ++() { --pos; return *this; } inline reverse_iterator operator ++(int) { auto tmp = *this; --*this; return tmp; } inline reverse_iterator & operator --() { ++pos; return *this; } inline reverse_iterator operator --(int) { auto tmp = *this; ++*this; return tmp; } inline reverse_iterator & operator +=(const reverse_iterator & it) { pos -= it.pos; return *this; } inline reverse_iterator & operator +=(size_t p) { pos -= p; return *this; } inline reverse_iterator & operator -=(const reverse_iterator & it) { pos += it.pos; return *this; } inline reverse_iterator & operator -=(size_t p) { pos += p; return *this; } friend inline reverse_iterator operator -(size_t p, const reverse_iterator & it) {return it - p;} friend inline reverse_iterator operator -(const reverse_iterator & it, size_t p) { auto tmp = it; tmp -= p; return tmp; } friend inline std::ptrdiff_t operator -(const reverse_iterator & it1, const reverse_iterator & it2) { return it2.pos - it1.pos; } friend inline reverse_iterator operator +(size_t p, const reverse_iterator & it) {return it + p;} friend inline reverse_iterator operator +(const reverse_iterator & it, size_t p) { auto tmp = it; tmp += p; return tmp; } inline bool operator ==(const reverse_iterator & it) const {return (pos == it.pos);} inline bool operator !=(const reverse_iterator & it) const {return (pos != it.pos);} friend inline bool operator <(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos < it2.pos; } friend inline bool operator <=(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos <= it2.pos; } friend inline bool operator >(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos > it2.pos; } friend inline bool operator >=(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos >= it2.pos; } }; class const_reverse_iterator { friend class PIDeque; private: inline const_reverse_iterator(const PIDeque * v, ssize_t p): parent(v), pos(p) {} const PIDeque * parent; ssize_t pos; public: typedef T value_type; typedef T* pointer; typedef T& reference; typedef std::ptrdiff_t difference_type; typedef std::random_access_iterator_tag iterator_category; inline const_reverse_iterator(): parent(0), pos(0) {} inline const T & operator *() const {return (*parent)[pos];} inline const T & operator ->() const {return (*parent)[pos];} inline const_reverse_iterator & operator ++() { --pos; return *this; } inline const_reverse_iterator operator ++(int) { auto tmp = *this; --*this; return tmp; } inline const_reverse_iterator & operator --() { ++pos; return *this; } inline const_reverse_iterator operator --(int) { auto tmp = *this; ++*this; return tmp; } inline const_reverse_iterator & operator +=(const const_reverse_iterator & it) { pos -= it.pos; return *this; } inline const_reverse_iterator & operator +=(size_t p) { pos -= p; return *this; } inline const_reverse_iterator & operator -=(const const_reverse_iterator & it) { pos += it.pos; return *this; } inline const_reverse_iterator & operator -=(size_t p) { pos += p; return *this; } friend inline const_reverse_iterator operator -(size_t p, const const_reverse_iterator & it) {return it - p;} friend inline const_reverse_iterator operator -(const const_reverse_iterator & it, size_t p) { auto tmp = it; tmp -= p; return tmp; } friend inline std::ptrdiff_t operator -(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it2.pos - it1.pos; } friend inline const_reverse_iterator operator +(size_t p, const const_reverse_iterator & it) {return it + p;} friend inline const_reverse_iterator operator +(const const_reverse_iterator & it, size_t p) { auto tmp = it; tmp += p; return tmp; } inline bool operator ==(const const_reverse_iterator & it) const {return (pos == it.pos);} inline bool operator !=(const const_reverse_iterator & it) const {return (pos != it.pos);} friend inline bool operator <(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos < it2.pos; } friend inline bool operator <=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos <= it2.pos; } friend inline bool operator >(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos > it2.pos; } friend inline bool operator >=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos >= it2.pos; } }; //! \~english Iterator to the first element. //! \~russian Итератор на первый элемент. //! \~\details ![begin, end](doc/images/pivector_begin.png) //! //! \~english If the array is empty, the returned iterator is equal to \a end(). //! \~russian Если массив - пуст, возвращаемый итератор будет равен \a end(). //! \~\return \ref stl_iterators //! \~\sa \a end(), \a rbegin(), \a rend() inline iterator begin() {return iterator(this, 0);} //! \~english Iterator to the element following the last element. //! \~russian Итератор на элемент, следующий за последним элементом. //! \~\details ![begin, end](doc/images/pivector_begin.png) //! //! \~english This element acts as a placeholder; //! attempting to access it results in undefined behavior. //! \~russian Этот элемент существует лишь условно, //! попытка доступа к нему приведёт к выходу за разрешенную память. //! \~\return \ref stl_iterators //! \~\sa \a begin(), \a rbegin(), \a rend() inline iterator end() {return iterator(this, pid_size);} inline const_iterator begin() const {return const_iterator(this, 0); } inline const_iterator end() const {return const_iterator(this, pid_size);} //! \~english Returns a reverse iterator to the first element of the reversed array. //! \~russian Обратный итератор на первый элемент. //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) //! //! \~english It corresponds to the last element of the non-reversed array. //! If the array is empty, the returned iterator is equal to \a rend(). //! \~russian Итератор для прохода массива в обратном порядке. //! Указывает на последний элемент. //! Если массив пустой, то совпадает с итератором \a rend(). //! \~\return \ref stl_iterators //! \~\sa \a rend(), \a begin(), \a end() inline reverse_iterator rbegin() {return reverse_iterator(this, pid_size - 1);} //! \~english Returns a reverse iterator to the element //! following the last element of the reversed array. //! \~russian Обратный итератор на элемент, следующий за последним элементом. //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) //! //! \~english It corresponds to the element preceding the first element of the non-reversed array. //! This element acts as a placeholder, attempting to access it results in undefined behavior. //! \~russian Итератор для прохода массива в обратном порядке. //! Указывает на элемент, предшествующий первому элементу. //! Этот элемент существует лишь условно, //! попытка доступа к нему приведёт к выходу за разрешенную память. //! \~\return \ref stl_iterators //! \~\sa \a rbegin(), \a begin(), \a end() inline reverse_iterator rend() {return reverse_iterator(this, -1);} inline const_reverse_iterator rbegin() const {return const_reverse_iterator(this, pid_size - 1);} inline const_reverse_iterator rend() const {return const_reverse_iterator(this, -1);} //! \~english Number of elements in the container. //! \~russian Количество элементов массива. //! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline size_t size() const {return pid_size;} //! \~english Number of elements in the container as signed value. //! \~russian Количество элементов массива в виде знакового числа. //! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline ssize_t size_s() const {return pid_size;} //! \~english Same as \a size(). //! \~russian Синоним \a size(). //! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline size_t length() const {return pid_size;} //! \~english Number of elements that the container has currently allocated space for. //! \~russian Количество элементов, для которого сейчас выделена память контейнером. //! \~\details //! \~english To find out the actual number of items, use the function \a size(). //! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size(). //! \~\sa \a reserve(), \a size(), \a size_s() inline size_t capacity() const {return pid_rsize;} inline size_t _start() const {return pid_start;} //! \~english Checks if the container has no elements. //! \~russian Проверяет пуст ли контейнер. //! \~\return //! \~english **true** if the container is empty, **false** otherwise //! \~russian **true** если контейнер пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isEmpty() const {return (pid_size == 0);} //! \~english Checks if the container has elements. //! \~russian Проверяет не пуст ли контейнер. //! \~\return //! \~english **true** if the container is not empty, **false** otherwise //! \~russian **true** если контейнер не пуст, **false** иначе. //! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve() inline bool isNotEmpty() const {return (pid_size > 0);} //! \~english Tests whether at least one element in the array //! passes the test implemented by the provided function `test`. //! \~russian Проверяет, удовлетворяет ли какой-либо элемент массива условию, //! заданному в передаваемой функции `test`. //! \~\return //! \~english **true** if, in the array, //! it finds an element for which the provided function returns **true**; //! otherwise it returns **false**. Always returns **false** if is empty. //! \~russian **true** если хотя бы для одного элемента //! передаваемая функция возвращает **true**, в остальных случаях **false**. //! Метод возвращает **false** при любом условии для пустого массива. //! \~\details //! \~\code //! PIDeque v{1, 2, 8, 9}; //! piCout << v.any([](int e){return e % 2 == 0;}); // true //! piCout << v.any([](int e){return e == 3;}); // false //! \endcode //! \~\sa \a every(), \a contains(), \a entries(), \a forEach() inline bool any(std::function test) const { for (ssize_t i = pid_start; i < pid_start + (ssize_t)pid_size; ++i) { if (test(pid_data[i])) return true; } return false; } //! \~english Tests whether all elements in the array passes the test //! implemented by the provided function `test`. //! \~russian Проверяет, удовлетворяют ли все элементы массива условию, //! заданному в передаваемой функции `test`. //! \~\return //! \~english **true** if, in the array, //! it finds an element for which the provided function returns **true**; //! otherwise it returns **false**. Always returns **true** if is empty. //! \~russian **true** если для всех элементов передаваемая функция возвращает **true**, //! в остальных случаях **false**. //! Метод возвращает **true** при любом условии для пустого массива. //! \~\details //! \~\code //! PIDeque v{1, 2, 8, 9}; //! piCout << v.every([](int e){return e % 2 == 0;}); // false //! piCout << v.every([](int e){return e > 0;}); // true //! \endcode //! \~\sa \a any(), \a contains(), \a entries(), \a forEach() inline bool every(std::function test) const { for (ssize_t i = pid_start; i < pid_start + (ssize_t)pid_size; ++i) { if (!test(pid_data[i])) return false; } return true; } //! \~english Full access to element by `index`. //! \~russian Полный доступ к элементу по индексу `index`. //! \~\details //! \~english Element index starts from `0`. //! Element index must be in range from `0` to `size()-1`. //! Otherwise will be undefined behavior. //! \~russian Индекс элемента считается от `0`. //! Индекс элемента должен лежать в пределах от `0` до `size()-1`. //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. //! \~\code //! PIDeque v{1, 2, 8, 9}; //! piCout << v[2]; // 8 //! v[2] = 5; //! piCout << v; // {1, 2, 5, 9} //! \endcode //! \~\sa \a at() inline T & operator [](size_t index) {return pid_data[pid_start + index];} inline const T & operator [](size_t index) const {return pid_data[pid_start + index];} //! \~english Read only access to element by `index`. //! \~russian Доступ исключительно на чтение к элементу по индексу `index`. //! \~\details //! \~english Element index starts from `0`. //! Element index must be in range from `0` to `size()-1`. //! Otherwise will be undefined behavior. //! \~russian Индекс элемента считается от `0`. //! Индекс элемента должен лежать в пределах от `0` до `size()-1`. //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. inline const T & at(size_t index) const {return pid_data[pid_start + index];} //! \~english Last element. //! \~russian Последний элемент массива. //! \~\details //! \~english Returns a reference to the last item in the array. //! This function assumes that the array isn't empty. //! Otherwise will be undefined behavior. //! \~russian Возвращает ссылку на последний элемент в массиве. //! Эта функция предполагает, что массив не пустой. //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. inline T & back() {return pid_data[pid_start + pid_size - 1];} inline const T & back() const {return pid_data[pid_start + pid_size - 1];} //! \~english Last element. //! \~russian Первый элемент массива. //! \~\details //! \~english Returns a reference to the last item in the array. //! This function assumes that the array isn't empty. //! Otherwise will be undefined behavior. //! \~russian Возвращает ссылку на пенрвый элемент в массиве. //! Эта функция предполагает, что массив не пустой. //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. inline T & front() {return pid_data[pid_start];} inline const T & front() const {return pid_data[pid_start];} //! \~english Compare operator with array `v`. //! \~russian Оператор сравнения с массивом `v`. inline bool operator ==(const PIDeque & v) const { if (pid_size != v.pid_size) return false; for (size_t i = 0; i < pid_size; ++i) { if (v[i] != (*this)[i]) return false; } return true; } //! \~english Compare operator with array `v`. //! \~russian Оператор сравнения с массивом `v`. inline bool operator !=(const PIDeque & v) const {return !(*this == v);} //! \~english Tests if element `e` exists in the array. //! \~russian Проверяет наличие элемента `e` в массиве. //! \~\details //! \~english Optional argument `start` - the position in this array at which to begin searching. //! If the index is greater than or equal to the array's size, //! **false** is returned, which means the array will not be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Note: if the provided index is negative, //! the array is still searched from front to back. //! Default: 0 (entire array is searched). //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. //! Если индекс больше или равен длине массива, //! возвращается **false**, что означает, что массив даже не просматривается. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. //! \~\code //! PIDeque v{1, 2, 3, 4}; //! piCout << v.contains(3); // true //! piCout << v.contains(5); // false //! piCout << v.contains(3, 3); // false //! piCout << v.contains(3, -2); // true //! piCout << v.contains(3, -99); // true //! \endcode //! \~\return //! \~english **true** if the array contains an occurrence of element `e`, //! otherwise it returns **false**. //! \~russian **true** если элемент `e` присутствует в массиве, //! в остальных случаях **false**. //! \~\sa \a every(), \a any(), \a entries(), \a forEach() inline bool contains(const T & e, ssize_t start = 0) const { if (start < 0) { start = pid_size + start; if (start < 0) start = 0; } for (ssize_t i = pid_start + start; i < pid_start + (ssize_t)pid_size; ++i) { if (e == pid_data[i]) return true; } return false; } //! \~english Count elements equal `e` in the array. //! \~russian Подсчитывает количество элементов, совпадающих с элементом `e` в массиве. //! \~\details //! \~english Optional argument `start` - the position in this array at which to begin searching. //! If the index is greater than or equal to the array's size, //! 0 is returned, which means the array will not be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Note: if the provided index is negative, //! the array is still searched from front to back. //! Default: 0 (entire array is searched). //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. //! Если индекс больше или равен длине массива, //! возвращается 0, что означает, что массив даже не просматривается. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. //! \~\code //! PIDeque v{2, 2, 4, 2, 6}; //! piCout << v.entries(2); // 3 //! piCout << v.entries(2, 2); // 1 //! piCout << v.entries(2, -4); // 2 //! \endcode //! \~\sa \a every(), \a any(), \a contains(), \a forEach(), \a indexOf() inline int entries(const T & e, size_t start = 0) const { int ec = 0; if (start < 0) { start = pid_size + start; if (start < 0) start = 0; } for (ssize_t i = pid_start + start; i < pid_start + (ssize_t)pid_size; ++i) { if (e == pid_data[i]) ++ec; } return ec; } //! \~english Count elements in the array passes the test implemented by the provided function `test`. //! \~russian Подсчитывает количество элементов в массиве, //! проходящих по условию, заданному в передаваемой функции `test`. //! \~\details //! \~english Overloaded function. //! Optional argument `start` - the position in this array at which to begin searching. //! If the index is greater than or equal to the array's size, //! 0 is returned, which means the array will not be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Note: if the provided index is negative, //! the array is still searched from front to back. //! Default: 0 (entire array is searched). //! \~russian Перегруженная функция. //! Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. //! Если индекс больше или равен длине массива, //! возвращается 0, что означает, что массив даже не просматривается. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. //! \~\sa \a every(), \a any(), \a contains(), \a forEach(), \a indexWhere() inline int entries(std::function test, size_t start = 0) const { int ec = 0; if (start < 0) { start = pid_size + start; if (start < 0) start = 0; } for (ssize_t i = pid_start + start; i < pid_start + (ssize_t)pid_size; ++i) { if (test(pid_data[i])) ++ec; } return ec; } //! \~english Returns the first index at which a given element `e` //! can be found in the array, or `-1` if it is not present. //! \~russian Возвращает первый индекс, по которому данный элемент `e` //! может быть найден в массиве или `-1`, если такого индекса нет. //! \~\details //! \~english Optional argument `start` - the position in this array at which to begin searching. //! If the index is greater than or equal to the array's size, //! `-1` is returned, which means the array will not be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Note: if the provided index is negative, //! the array is still searched from front to back. //! Default: 0 (entire array is searched). //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. //! Если индекс больше или равен длине массива, //! возвращается `-1`, что означает, что массив даже не просматривается. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. //! \~\code //! PIDeque v{2, 5, 9}; //! piCout << v.indexOf(2); // 0 //! piCout << v.indexOf(7); // -1 //! piCout << v.indexOf(9, 2); // 2 //! piCout << v.indexOf(2, -1); // -1 //! piCout << v.indexOf(2, -3); // 0 //! \endcode //! \~\sa \a indexWhere(), \a lastIndexOf(), \a lastIndexWhere(), \a contains() inline ssize_t indexOf(const T & e, size_t start = 0) const { if (start < 0) { start = pid_size + start; if (start < 0) start = 0; } for (ssize_t i = pid_start + start; i < pid_start + (ssize_t)pid_size; ++i) { if (e == pid_data[i]) { return i - pid_start; } } return -1; } //! \~english Returns the first index passes the test implemented by the provided function `test`, //! or `-1` if it is not present. //! can be found in the array, or `-1` if it is not present. //! \~russian Возвращает первый индекс элемента проходящего по условию, //! заданному в передаваемой функции `test`, или `-1`, если таких элементов нет. //! \~\details //! \~english Optional argument `start` - the position in this array at which to begin searching. //! If the index is greater than or equal to the array's size, //! `-1` is returned, which means the array will not be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Note: if the provided index is negative, //! the array is still searched from front to back. //! Default: 0 (entire array is searched). //! \~russian Опциональный аргумент `start` указывает на индекс в массиве, откуда будет начинаться поиск. //! Если индекс больше или равен длине массива, //! возвращается `-1`, что означает, что массив даже не просматривается. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Если рассчитанный индекс все равно оказывается меньше 0, просматривается весь массив. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от начала к концу. //! Значение по умолчанию равно 0, что означает, что просматривается весь массив. //! \~\code //! PIDeque v{"do", "re", "mi", "re"}; //! piCout << v.indexWhere([](const PIString & s){return s.startsWith('r');}); // 1 //! piCout << v.indexWhere([](const PIString & s){return s.startsWith('r');}, 2); // 3 //! piCout << v.indexWhere([](const PIString & s){return s.startsWith('k');}); // -1 //! \endcode //! \~\sa \a indexOf(), \a lastIndexOf(), \a lastIndexWhere(), \a contains() inline ssize_t indexWhere(std::function test, size_t start = 0) const { if (start < 0) { start = pid_size + start; if (start < 0) start = 0; } for (ssize_t i = pid_start + start; i < pid_start + (ssize_t)pid_size; ++i) { if (test(pid_data[i])) { return i - pid_start; } } return -1; } //! \~english Returns the last index at which a given element `e` //! can be found in the array, or `-1` if it is not present. //! \~russian Возвращает последний индекс, по которому данный элемент `e` //! может быть найден в массиве или `-1`, если такого индекса нет. //! \~\details //! \~english Optional argument `start` - the position in this array //! at which to start searching backwards. //! If the index is greater than or equal to the array's size, //! causes the whole array to be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Therefore, if calculated index less than 0, //! the array is not searched, and the method returns `-1`. //! Note: if the provided index is negative, //! the array is still searched from back to front. //! Default: -1 (entire array is searched). //! \~russian Опциональный аргумент `start` указывает на индекс //! c которого начинать поиск в обратном направлении. //! Если индекс больше или равен длине массива, просматривается весь массив. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от конца к началу. //! Если рассчитанный индекс оказывается меньше 0, массив даже не просматривается. //! Значение по умолчанию равно `-1`, что равно индексу последнего элемента //! и означает, что просматривается весь массив. //! \~\code //! PIDeque v{2, 5, 9, 2}; //! piCout << v.lastIndexOf(2); // 3 //! piCout << v.lastIndexOf(7); // -1 //! piCout << v.lastIndexOf(2, 2); // 0 //! piCout << v.lastIndexOf(2, -3); // 0 //! piCout << v.lastIndexOf(2, -300); // -1 //! piCout << v.lastIndexOf(2, 300); // 3 //! \endcode //! \~\sa \a indexOf(), \a indexWhere(), \a lastIndexWhere(), \a contains() inline ssize_t lastIndexOf(const T & e, ssize_t start = -1) const { if (start >= size_s()) start = pid_size - 1; if (start < 0) start = pid_size + start; for (ssize_t i = pid_start + start; i >= pid_start; --i) { if (e == pid_data[i]) { return i - pid_start; } } return -1; } //! \~english Returns the last index passes the test implemented by the provided function `test`, //! or `-1` if it is not present. //! \~russian Возвращает последний индекс элемента проходящего по условию, //! заданному в передаваемой функции `test`, или `-1`, если таких элементов нет. //! \~\details //! \~english Optional argument `start` - the position in this array //! at which to start searching backwards. //! If the index is greater than or equal to the array's size, //! causes the whole array to be searched. //! If the provided index value is a negative number, //! it is taken as the offset from the end of the array. //! Therefore, if calculated index less than 0, //! the array is not searched, and the method returns `-1`. //! Note: if the provided index is negative, //! the array is still searched from back to front. //! Default: -1 (entire array is searched). //! \~russian Опциональный аргумент `start` указывает на индекс //! c которого начинать поиск в обратном направлении. //! Если индекс больше или равен длине массива, просматривается весь массив. //! Если индекс является отрицательным числом, он трактуется как смещение с конца массива. //! Обратите внимание: если индекс отрицателен, массив всё равно просматривается от конца к началу. //! Если рассчитанный индекс оказывается меньше 0, массив даже не просматривается. //! Значение по умолчанию равно `-1`, что равно индексу последнего элемента //! и означает, что просматривается весь массив. //! \~\sa \a indexOf(), \a lastIndexOf(), \a indexWhere(), \a contains() inline ssize_t lastIndexWhere(std::function test, ssize_t start = -1) const { if (start >= size_s()) start = pid_size - 1; if (start < 0) start = pid_size + start; for (ssize_t i = pid_start + start; i >= pid_start; --i) { if (test(pid_data[i])) { return i - pid_start; } } return -1; } //! \~english Pointer to array //! \~russian Указатель на память массива //! \~\details //! \~english Optional argument `index` the position in this array, //! where is pointer. Default: start of array. //! \~russian Опциональный аргумент `index` указывает на индекс c которого брать указатель. //! По умолчанию указывает на начало массива. //! \~\code //! PIDeque v{2, 5, 9, 2}; //! int a[2] = {12, 13}; //! memcpy(vec.data(1), a, 2 * sizeof(int)); //! piCout << v; // {2, 12, 13, 2} //! \endcode inline T * data(size_t index = 0) {return &(pid_data[pid_start + index]);} //! \~english Read only pointer to array //! \~russian Указатель на память массива только для чтения. //! \~\details //! \~english The pointer can be used to access and modify the items in the array. //! The pointer remains valid as long as the array isn't reallocated. //! Optional argument `index` the position in this array, //! where is pointer. Default: start of array. //! \~russian Указатель можно использовать для доступа и изменения элементов в массиве. //! Указатель остается действительным только до тех пор, пока массив не будет перераспределен. //! Опциональный аргумент `index` указывает на индекс c которого брать указатель. //! По умолчанию указывает на начало массива. //! \~\code //! PIDeque v{1, 3, 5}; //! int a[3]; //! memcpy(a, v.data(), a.size() * sizeof(int)); //! piCout << a[0] << a[1] << a[2]; // 1 3 5 //! \endcode inline const T * data(size_t index = 0) const {return &(pid_data[pid_start + index]);} //! \~english Creates sub-array of this array. //! \~russian Создает подмассив, то есть кусок из текущего массива. //! \~english //! \param index - index of this array where sub-array starts //! \param count - sub-array size //! \~russian //! \param index - индекс в текущем массиве, откуда начинётся подмассив //! \param count - размер подмассива //! \~\details //! \~english //! Index must be in range from `0` to `size()-1`. //! If sub-array size more than this array size, than ends early. //! \~russian //! Индекс начала должен лежать в диапазоне от `0` до `size()-1`. //! Если заданный размер подмассива превышает размер текущего массива, //! то вернется подмассив меньшего размера (`size()-index-1`). PIDeque getRange(size_t index, size_t count) const { if (index >= pid_size || count == 0) return PIDeque(); if (index + count > pid_size) count = pid_size - index; return PIDeque(&(pid_data[pid_start + index]), count); } //! \~english Clear array, remove all elements. //! \~russian Очищает массив, удаляет все элементы. //! \~\details //! \~\note //! \~english Reserved memory will not be released. //! \~russian Зарезервированная память не освободится. //! \~\sa \a resize() template::value , int>::type = 0> inline PIDeque & clear() { resize(0); return *this; } template::value , int>::type = 0> inline PIDeque & clear() { PIINTROSPECTION_CONTAINER_UNUSED(T, pid_size) pid_size = 0; pid_start = (pid_rsize - pid_size) / 2; return *this; } //! \~english Assigns element 'e' to all items in the array. //! \~russian Заполняет весь массив копиями элемента 'e'. //! \~\details //! \code //! PIDeque v{1, 3, 5}; //! v.fill(7); //! piCout << v; // {7, 7, 7} //! \endcode //! \~\sa \a resize() inline PIDeque & fill(const T & e = T()) { deleteT(pid_data + pid_start, pid_size); PIINTROSPECTION_CONTAINER_USED(T, pid_size) for (size_t i = pid_start; i < pid_start + pid_size; ++i) { elementNew(pid_data + i, e); } return *this; } //! \~english Assigns result of function 'f(size_t i)' to all items in the array. //! \~russian Заполняет весь массив результатом вызова функции 'f(size_t i)'. //! \~\details //! \code //! PIDeque v{1, 3, 5}; //! v.fill([](size_t i){return i*2;}); //! piCout << v; // {0, 2, 4} //! \endcode //! \~\sa \a resize() inline PIDeque & fill(std::function f) { deleteT(pid_data + pid_start, pid_size); PIINTROSPECTION_CONTAINER_USED(T, pid_size) for (size_t i = pid_start; i < pid_start + pid_size; ++i) { elementNew(pid_data + i, f(i)); } return *this; } //! \~english Same as \a fill(). //! \~russian Тоже самое что и \a fill(). //! \~\sa \a fill(), \a resize() inline PIDeque & assign(const T & e = T()) {return fill(e);} //! \~english First does `resize(new_size)` then `fill(e)`. //! \~russian Сначала делает `resize(new_size)`, затем `fill(e)`. //! \~\sa \a fill(), \a resize() template::value , int>::type = 0> inline PIDeque & assign(size_t new_size, const T & e) { resize(new_size); return fill(e); } template::value , int>::type = 0> inline PIDeque & assign(size_t new_size, const T & e) { _resizeRaw(new_size); return fill(e); } //! \~english Sets size of the array, new elements are copied from `e`. //! \~russian Устанавливает размер массива, новые элементы копируются из `e`. //! \~\details //! \~english If `new_size` is greater than the current \a size(), //! elements are added to the end; the new elements are initialized from `e`. //! If `new_size` is less than the current \a size(), elements are removed from the end. //! \~russian Если `new_size` больше чем текущий размер массива \a size(), //! новые элементы добавляются в конец массива и создаются из `e`. //! Если `new_size` меньше чем текущий размер массива \a size(), //! лишние элементы удаляются с конца массива. //! \~\sa \a size(), \a clear() inline PIDeque & resize(size_t new_size, const T & e = T()) { if (new_size < pid_size) { deleteT(&(pid_data[new_size + pid_start]), pid_size - new_size); pid_size = new_size; if (new_size == 0) { pid_start = (pid_rsize - pid_size) / 2; } } if (new_size > pid_size) { size_t os = pid_size; alloc_forward(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size-os)) for (size_t i = os + pid_start; i < new_size + pid_start; ++i) { elementNew(pid_data + i, e); } } return *this; } //! \~english Sets size of the array, new elements created by function `f(size_t i)`. //! \~russian Устанавливает размер массива, новые элементы создаются функцией `f(size_t i)`. //! \~\details //! \~english If `new_size` is greater than the current \a size(), //! elements are added to the end; the new elements created by function `f(size_t i)`. //! If `new_size` is less than the current \a size(), elements are removed from the end. //! \~russian Если `new_size` больше чем текущий размер массива \a size(), //! новые элементы добавляются в конец массива и функцией `f(size_t i)`. //! Если `new_size` меньше чем текущий размер массива \a size(), //! лишние элементы удаляются с конца массива. //! \~\sa \a size(), \a clear() inline PIDeque & resize(size_t new_size, std::function f) { if (new_size < pid_size) { deleteT(&(pid_data[new_size + pid_start]), pid_size - new_size); pid_size = new_size; if (new_size == 0) { pid_start = (pid_rsize - pid_size) / 2; } } if (new_size > pid_size) { size_t os = pid_size; alloc_forward(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size-os)) for (size_t i = os + pid_start; i < new_size + pid_start; ++i) { elementNew(pid_data + i, f(i)); } } return *this; } template::value , int>::type = 0> inline PIDeque & _resizeRaw(size_t new_size) { if (new_size > pid_size) { PIINTROSPECTION_CONTAINER_USED(T, (new_size-pid_size)); } if (new_size < pid_size) { PIINTROSPECTION_CONTAINER_UNUSED(T, (pid_size-new_size)); } alloc_forward(new_size); return *this; } inline void _copyRaw(T * dst, const T * src, size_t size) { newT(dst, src, size); } //! \~english Attempts to allocate memory for at least `new_size` elements. //! \~russian Резервируется память под как минимум `new_size` элементов. //! \~\details //! \~english If you know in advance how large the array will be, //! you should call this function to prevent reallocations and memory fragmentation. //! If `new_size` is greater than the current \a capacity(), //! new storage is allocated, otherwise the function does nothing. //! This function does not change the \a size() of the array. //! \~russian Если вы заранее знаете, насколько велик будет массив, //! вы можете вызвать эту функцию, чтобы предотвратить перераспределение и фрагментацию памяти. //! Если размер `new_size` больше чем выделенная память \a capacity(), //! то произойдёт выделение новой памяти и перераспределение массива. //! Эта функция не изменяет количество элементов в массиве \a size(). //! \~\sa \a size(), \a capacity(), \a resize() inline PIDeque & reserve(size_t new_size) { if (new_size <= pid_rsize) return *this; size_t os = pid_size; alloc_forward(new_size); pid_size = os; return *this; } //! \~english Inserts value `e` at `index` position in the array. //! \~russian Вставляет значение `e` в позицию `index` в массиве. //! \~\details //! \~english The index must be greater than 0 and less than or equal to \a size(). //! \~russian Индекс должен быть больше 0 и меньше или равен \a size(). //! \code //! PIDeque v{1, 3, 5}; //! v.insert(2, 7); //! piCout << v; // {1, 3, 7, 5} //! \endcode //! \~\sa \a append(), \a prepend(), \a remove() inline PIDeque & insert(size_t index, const T & e = T()) { if (index == pid_size) return push_back(e); PIINTROSPECTION_CONTAINER_USED(T, 1) bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { alloc_forward(pid_size + 1); if (index < pid_size - 1) { size_t os = pid_size - index - 1; memmove((void*)(&(pid_data[index + pid_start + 1])), (const void*)(&(pid_data[index + pid_start])), os * sizeof(T)); } } else { alloc_backward(pid_size + 1, -1); if (index > 0) { memmove((void*)(&(pid_data[pid_start])), (const void*)(&(pid_data[pid_start + 1])), index * sizeof(T)); } } elementNew(pid_data + pid_start + index, e); return *this; } //! \~english Inserts value `e` at `index` position in the array. //! \~russian Вставляет значение `e` в позицию `index` в массиве. //! \~\details //! \~english The index must be greater than 0 and less than or equal to \a size(). //! \~russian Индекс должен быть больше 0 и меньше или равен \a size(). //! \~\sa \a append(), \a prepend(), \a remove() inline PIDeque & insert(size_t index, T && e) { if (index == pid_size) return push_back(e); PIINTROSPECTION_CONTAINER_USED(T, 1) bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { alloc_forward(pid_size + 1); if (index < pid_size - 1) { size_t os = pid_size - index - 1; memmove((void*)(&(pid_data[index + pid_start + 1])), (const void*)(&(pid_data[index + pid_start])), os * sizeof(T)); } } else { alloc_backward(pid_size + 1, -1); if (index > 0) { memmove((void*)(&(pid_data[pid_start])), (const void*)(&(pid_data[pid_start + 1])), index * sizeof(T)); } } elementNew(pid_data + pid_start + index, std::move(e)); return *this; } //! \~english Inserts array `v` at `index` position in the array. //! \~russian Вставляет массив `v` в позицию `index` в массиве. //! \~\details //! \~english The index must be greater than or equal to 0 and less than or equal to \a size(). //! \~russian Индекс должен быть больше или равен 0 и меньше или равен \a size(). //! \~\sa \a append(), \a prepend(), \a remove() inline PIDeque & insert(size_t index, const PIDeque & v) { if (v.isEmpty()) return *this; #ifndef NDEBUG if (&v == this) { printf("error with PIDeque<%s>::insert\n", __PIP_TYPENAME__(T)); } #endif assert(&v != this); bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { ssize_t os = pid_size - index; alloc_forward(pid_size + v.pid_size); if (os > 0) { memmove((void*)(&(pid_data[index + pid_start + v.pid_size])), (const void*)(&(pid_data[index + pid_start])), os * sizeof(T)); } } else { alloc_backward(pid_size + v.pid_size, -v.pid_size); if (index > 0) { memmove((void*)(&(pid_data[pid_start])), (const void*)(&(pid_data[pid_start + v.pid_size])), index * sizeof(T)); } } newT(pid_data + pid_start + index, v.pid_data + v.pid_start, v.pid_size); return *this; } //! \~english Inserts the given elements at `index` position in the array. //! \~russian Вставляет элементы в позицию `index` в массиве. //! \~\details //! \~english The index must be greater than or equal to 0 and less than or equal to \a size(). //! Inserts the given elements from //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). //! \~russian Индекс должен быть больше или равен 0 и меньше или равен \a size(). //! Вставляет элементы из //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). //! \~\sa \a append(), \a prepend(), \a remove() inline PIDeque & insert(size_t index, std::initializer_list init_list) { bool dir = pid_rsize <= 2 ? true : (index >= pid_rsize / 2 ? true : false); if (dir) { ssize_t os = pid_size - index; alloc_forward(pid_size + init_list.size()); if (os > 0) { memmove((void*)(&(pid_data[index + pid_start + init_list.size()])), (const void*)(&(pid_data[index + pid_start])), os * sizeof(T)); } } else { alloc_backward(pid_size + init_list.size(), -init_list.size()); if (index > 0) { memmove((void*)(&(pid_data[pid_start])), (const void*)(&(pid_data[pid_start + init_list.size()])), index * sizeof(T)); } } newT(pid_data + pid_start + index, init_list.begin(), init_list.size()); return *this; } //! \~english Removes `count` elements from the middle of the array, starting at `index` position. //! \~russian Удаляет элементы из массива, начиная с позиции `index` в количестве `count`. //! \~\details //! \code //! PIDeque v{1, 3, 7, 5}; //! v.remove(1, 2); //! piCout << v; // {1, 5} //! \endcode //! \~\sa \a resize(), \a insert(), \a removeOne(), \a removeAll(), \a removeWhere() inline PIDeque & remove(size_t index, size_t count = 1) { if (count == 0) return *this; if (index + count >= pid_size) { resize(index); return *this; } size_t os = pid_size - index - count; deleteT(&(pid_data[index + pid_start]), count); if (os <= index) { if (os > 0) { memmove((void*)(&(pid_data[index + pid_start])), (const void*)(&(pid_data[index + pid_start + count])), os * sizeof(T)); } } else { if (index > 0) { memmove((void*)(&(pid_data[pid_start + count])), (const void*)(&(pid_data[pid_start])), index * sizeof(T)); } pid_start += count; } pid_size -= count; return *this; } //! \~english Swaps array `v` other with this array. //! \~russian Меняет местами массив `v` с этим массивом. //! \~\details //! \~english This operation is very fast and never fails. //! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев. inline void swap(PIDeque & other) { piSwap(pid_data, other.pid_data); piSwap(pid_size, other.pid_size); piSwap(pid_rsize, other.pid_rsize); piSwap(pid_start, other.pid_start); } //! \~english Sorts the elements in non-descending order. //! \~russian Сортировка элементов в порядке возрастания. //! \~\details //! \~english The order of equal elements is not guaranteed to be preserved. //! Elements are compared using operator<. //! Sorting provided by [std::sort](https://en.cppreference.com/w/cpp/algorithm/sort). //! Complexity `O(N·log(N))`. //! \~russian Сохранность порядка элементов, имеющих одинаковое значение, не гарантируется. //! Для сравнения элементов используется оператор `operator<`. //! Для сортировки используется функция [std::sort](https://ru.cppreference.com/w/cpp/algorithm/sort). //! Сложность сортировки `O(N·log(N))`. //! \~\code //! PIDeque v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; //! v.sort(); //! piCout << v; // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 //! \endcode //! \~\sa \a sort(std::function comp) inline PIDeque & sort() { std::sort(begin(), end()); return *this; } //! \~english Sorts the elements in non-descending order. //! \~russian Сортировка элементов в порядке возрастания. //! \~\details //! \~english The order of equal elements is not guaranteed to be preserved. //! Elements are compared using the given binary comparison function `comp`. //! which returns `​true` if the first argument is less than (i.e. is ordered before) the second. //! The signature of the comparison function should be equivalent to the following: //! \code //! bool comp(const T &a, const T &b); //! \endcode //! While the signature does not need to have const &, the function must not modify the objects passed to it. //! The function must return `false` for identical elements, //! otherwise, it will lead to undefined program behavior and memory errors. //! Sorting provided by [std::sort](https://en.cppreference.com/w/cpp/algorithm/sort). //! Complexity `O(N·log(N))`. //! \~russian Сохранность порядка элементов, имеющих одинаковое значение, не гарантируется. //! Для сравнения элементов используется функция сравнения `comp`. //! Функция сравнения, возвращает ​`true` если первый аргумент меньше второго. //! Сигнатура функции сравнения должна быть эквивалентна следующей: //! \code //! bool comp(const T &a, const T &b); //! \endcode //! Сигнатура не обязана содержать const &, однако, функция не может изменять переданные объекты. //! Функция обязана возвращать `false` для одинаковых элементов, //! иначе это приведёт к неопределённому поведению программы и ошибкам памяти. //! Для сортировки используется функция [std::sort](https://ru.cppreference.com/w/cpp/algorithm/sort). //! Сложность сортировки `O(N·log(N))`. //! \~\code //! PIDeque v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; //! v.sort([](const int & a, const int & b){return a > b;}); //! piCout << v; // 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 //! \endcode //! \~\sa \a sort() inline PIDeque & sort(std::function comp) { std::sort(begin(), end(), comp); return *this; } //! \~english Reverses this array. //! \~russian Обращает порядок следования элементов этого массива. //! \~\details //! \~english This method reverses an array [in place](https://en.wikipedia.org/wiki/In-place_algorithm). //! The first array element becomes the last, and the last array element becomes the first. //! The reverse method transposes the elements of the calling array object in place, //! mutating the array, and returning a reference to the array. //! \~russian Метод reverse() на месте переставляет элементы массива, //! на котором он был вызван, изменяет массив и возвращает ссылку на него. //! Первый элемент массива становится последним, а последний — первым. //! \~\code //! PIDeque v{1, 3, 7, 5}; //! v.reverse(); //! piCout << v; // {5, 7, 3, 1} //! \endcode //! \~\sa \a reversed() inline PIDeque & reverse() { size_t s2 = pid_size/2; for (size_t i = 0; i < s2; ++i) { piSwap(pid_data[pid_start+i], pid_data[pid_start+pid_size-i-1]); } return *this; } //! \~english Returns reversed array. //! \~russian Возвращает перевернутый массив. //! \~\details //! \~english Returns a copy of the array with elements in reverse order. //! The first array element becomes the last, and the last array element becomes the first. //! \~russian Возвращает копию массива с элементами в обратном порядке. //! Первый элемент массива становится последним, а последний — первым. //! \~\sa \a reverse() inline PIDeque reversed() const { PIDeque ret(*this); return ret.reverse(); } //! \~english Increases or decreases the size of the array by `add_size` elements. //! \~russian Увеличивает или уменьшает размер массива на `add_size` элементов. //! \~\details //! \~english If `add_size > 0` then elements are added to the end of the array. //! If `add_size < 0` then elements are removed from the end of the array. //! If `add_size < 0` and there are fewer elements in the array than specified, then the array becomes empty. //! \~russian Если `add_size > 0`, то в конец массива добавляются элементы. //! Если `add_size < 0`, то с конца массива удаляются элементы. //! Если `add_size < 0` и в массиве меньше элементов чем указано, то массив становится пустым. //! \~\sa \a resize() inline PIDeque & enlarge(llong pid_size) { llong ns = size_s() + pid_size; if (ns <= 0) clear(); else resize(size_t(ns)); return *this; } //! \~english Remove no more than one element equal `e`. //! \~russian Удаляет первый элемент, который равен элементу `e`. //! \~\details //! \~\code //! PIDeque v{3, 2, 5, 2, 7}; //! v.removeOne(2); //! piCout << v; // {3, 5, 2, 7} //! \endcode //! \~\sa \a remove(), \a removeAll(), \a removeWhere() inline PIDeque & removeOne(const T & e) { for (size_t i = 0; i < pid_size; ++i) { if (pid_data[i + pid_start] == e) { remove(i); return *this; } } return *this; } //! \~english Remove all elements equal `e`. //! \~russian Удаляет все элементы, равные элементу `e`. //! \~\details //! \~\code //! PIDeque v{3, 2, 5, 2, 7}; //! v.removeAll(2); //! piCout << v; // {3, 5, 7} //! \endcode //! \~\sa \a remove(), \a removeOne(), \a removeWhere() inline PIDeque & removeAll(const T & e) { for (ssize_t i = 0; i < ssize_t(pid_size); ++i) { if (pid_data[i + pid_start] == e) { remove(i); --i; } } return *this; } //! \~english Remove all elements in the array //! passes the test implemented by the provided function `test`. //! \~russian Удаляет все элементы, удовлетворяющие условию, //! заданному в передаваемой функции `test`. //! \~\details //! \~\code //! PIDeque v{3, 2, 5, 2, 7}; //! v.removeWhere([](const int & i){return i > 2;}); //! piCout << v; // {2, 2} //! \endcode //! \~\sa \a remove(), \a removeOne(), \a removeWhere() inline PIDeque & removeWhere(std::function test) { for (ssize_t i = 0; i < ssize_t(pid_size); ++i) { if (test(pid_data[i + pid_start])) { remove(i); --i; } } return *this; } //! \~english Appends the given element `e` to the end of the array. //! \~russian Добавляет элемент `e` в конец массива. //! \~\details //! \~english If size() is less than capacity(), which is most often //! then the addition will be very fast. //! In any case, the addition is fast and does not depend on the size of the array. //! If the new size() is greater than capacity() //! then all iterators and references //! (including the past-the-end iterator) are invalidated. //! Otherwise only the past-the-end iterator is invalidated. //! \~russian Если size() меньше capacity(), что часто бывает, //! то добавление будет очень быстрым. //! В любом случае добавление быстрое и не зависит от размера массива. //! Если новый size() больше, чем capacity(), //! то все итераторы и указатели становятся нерабочими. //! В противном случае все, кроме итераторов, указывающих на конец массива, //! остаются в рабочем состоянии. //! \~\code //! PIDeque v{1, 2, 3}; //! v.push_back(4); //! v.push_back(5); //! piCout << v; // {1, 2, 3, 4, 5} //! \endcode //! \~\sa \a push_front(), \a append(), \a prepend(), \a insert() inline PIDeque & push_back(const T & e) { alloc_forward(pid_size + 1); PIINTROSPECTION_CONTAINER_USED(T, 1); elementNew(pid_data + pid_start + pid_size - 1, e); return *this; } //! \~english Appends the given element `e` to the end of the array. //! \~russian Добавляет элемент `e` в конец массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\sa \a push_back() inline PIDeque & push_back(T && e) { alloc_forward(pid_size + 1); PIINTROSPECTION_CONTAINER_USED(T, 1); elementNew(pid_data + pid_start + pid_size - 1, std::move(e)); return *this; } //! \~english Appends the given elements to the end of the array. //! \~russian Добавляет элементы в конец массива. //! \~\details //! \~english Overloaded function. //! Appends the given elements from //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). //! \~russian Перегруженая функция. //! Добавляет элементы из //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). //! \~\sa \a push_back() inline PIDeque & push_back(std::initializer_list init_list) { size_t ps = pid_size; alloc_forward(pid_size + init_list.size()); newT(pid_data + pid_start + ps, init_list.begin(), init_list.size()); return *this; } //! \~english Appends the given array `v` to the end of the array. //! \~russian Добавляет массив `v` в конец массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\sa \a push_back() inline PIDeque & push_back(const PIDeque & v) { #ifndef NDEBUG if (&v == this) { printf("error with PIDeque<%s>::append\n", __PIP_TYPENAME__(T)); } #endif assert(&v != this); size_t ps = pid_size; alloc_forward(pid_size + v.pid_size); newT(pid_data + ps + pid_start, v.pid_data + v.pid_start, v.pid_size); return *this; } //! \~english Appends the given element `e` to the end of the array. //! \~russian Добавляет элемент `e` в конец массива. //! \~\details //! \~english If size() is less than capacity(), which is most often //! then the addition will be very fast. //! In any case, the addition is fast and does not depend on the size of the array. //! If the new size() is greater than capacity() //! then all iterators and references //! (including the past-the-end iterator) are invalidated. //! Otherwise only the past-the-end iterator is invalidated. //! \~russian Если size() меньше capacity(), что часто бывает, //! то добавление будет очень быстрым. //! В любом случае добавление быстрое и не зависит от размера массива. //! Если новый size() больше, чем capacity(), //! то все итераторы и указатели становятся нерабочими. //! В противном случае все, кроме итераторов, указывающих на конец массива, //! остаются в рабочем состоянии. //! \~\code //! PIDeque v{1, 2, 3}; //! v.append(4); //! v.append(5); //! piCout << v; // {1, 2, 3, 4, 5} //! \endcode //! \~\sa \a prepend(), \a push_front(), \a push_back(), \a insert() inline PIDeque & append(const T & e) {return push_back(e);} //! \~english Appends the given element `e` to the end of the array. //! \~russian Добавляет элемент `e` в конец массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\sa \a append() inline PIDeque & append(T && e) {return push_back(std::move(e));} //! \~english Appends the given elements to the end of the array. //! \~russian Добавляет элементы в конец массива. //! \~\details //! \~english Overloaded function. //! Appends the given elements from //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). //! \~russian Перегруженая функция. //! Добавляет элементы из //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). //! \~\sa \a append() inline PIDeque & append(std::initializer_list init_list) {return push_back(init_list);} //! \~english Appends the given array `v` to the end of the array. //! \~russian Добавляет массив `v` в конец массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\code //! PIDeque v{1, 2, 3}; //! v.append(PIDeque{4, 5}); //! piCout << v; // {1, 2, 3, 4, 5} //! \endcode //! \~\sa \a append() inline PIDeque & append(const PIDeque & v) {return push_back(v);} //! \~english Appends the given element `e` to the end of the array. //! \~russian Добавляет элемент `e` в конец массива. //! \~\details //! \~\code //! PIDeque v{1, 2, 3}; //! v << 4 << 5; //! piCout << v; // {1, 2, 3, 4, 5} //! \endcode //! \~\sa \a append() inline PIDeque & operator <<(const T & e) {return push_back(e);} //! \~english Appends the given element `e` to the end of the array. //! \~russian Добавляет элемент `e` в конец массива. //! \~\details //! \~\code //! PIDeque v{1, 2, 3}; //! v << 4 << 5; //! piCout << v; // {1, 2, 3, 4, 5} //! \endcode //! \~\sa \a append() inline PIDeque & operator <<(T && e) {return push_back(std::move(e));} //! \~english Appends the given array `v` to the end of the array. //! \~russian Добавляет массив `v` в конец массива. //! \~\details //! \~\code //! PIDeque v{1, 2, 3}; //! v << PIDeque{4, 5}; //! piCout << v; // {1, 2, 3, 4, 5} //! \endcode //! \~\sa \a append(), \a push_back() inline PIDeque & operator <<(const PIDeque & v) {return append(v);} //! \~english Appends the given element `e` to the begin of the array. //! \~russian Добавляет элемент `e` в начало массива. //! \~\details //! \~english If there is free space at the beginning of the array, //! which is most often, then the addition will be very fast. //! In any case, the addition is fast and does not depend on the size of the array. //! If there is no free space at the beginning of the array //! then all iterators and references //! (including the past-the-begin iterator) are invalidated. //! Otherwise only the past-the-begin iterator is invalidated. //! \~russian Если в начале массива имеется свободное место, //! что часто бывает, то добавление будет очень быстрым. //! В любом случае добавление быстрое и не зависит от размера массива. //! Если в начале массива нет свободного места, //! то все итераторы и указатели становятся нерабочими. //! В противном случае все, кроме итераторов указывающих, на начало массива, //! остаются в рабочем состоянии. //! \~\code //! PIDeque v{1, 2, 3}; //! v.push_front(4); //! v.push_front(5); //! piCout << v; // {5, 4, 1, 2, 3} //! \endcode //! \~\sa \a push_back(), \a append(), \a prepend(), \a insert() inline PIDeque & push_front(const T & e) { insert(0, e); return *this; } //! \~english Appends the given element `e` to the begin of the array. //! \~russian Добавляет элемент `e` в начало массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\sa \a push_front() inline PIDeque & push_front(T && e) { insert(0, std::move(e)); return *this; } //! \~english Appends the given array `v` to the begin of the array. //! \~russian Добавляет массив `v` в начало массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\code //! PIDeque v{1, 2, 3}; //! v.push_front(PIDeque{4, 5}); //! piCout << v; // {4, 5, 1, 2, 3} //! \endcode //! \~\sa \a push_front() inline PIDeque & push_front(const PIDeque & v) { insert(0, v); return *this; } //! \~english Appends the given elements to the begin of the array. //! \~russian Добавляет элементы в начало массива. //! \~\details //! \~english Overloaded function. //! Appends the given elements from //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). //! \~russian Перегруженая функция. //! Добавляет элементы из //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). //! \~\sa \a append() inline PIDeque & push_front(std::initializer_list init_list) { insert(0, init_list); return *this; } //! \~english Appends the given element `e` to the begin of the array. //! \~russian Добавляет элемент `e` в начало массива. //! \~\details //! \~english If there is free space at the beginning of the array, //! which is most often, then the addition will be very fast. //! In any case, the addition is fast and does not depend on the size of the array. //! If there is no free space at the beginning of the array //! then all iterators and references //! (including the past-the-begin iterator) are invalidated. //! Otherwise only the past-the-begin iterator is invalidated. //! \~russian Если в начале массива имеется свободное место, //! что часто бывает, то добавление будет очень быстрым. //! В любом случае добавление быстрое и не зависит от размера массива. //! Если в начале массива нет свободного места, //! то все итераторы и указатели становятся нерабочими. //! В противном случае все, кроме итераторов указывающих, на начало массива, //! остаются в рабочем состоянии. //! \~\code //! PIDeque v{1, 2, 3}; //! v.prepend(4); //! v.prepend(5); //! piCout << v; // {5, 4, 1, 2, 3} //! \endcode //! \~\sa \a push_back(), \a append(), \a prepend(), \a insert() inline PIDeque & prepend(const T & e) {return push_front(e);} //! \~english Appends the given element `e` to the begin of the array. //! \~russian Добавляет элемент `e` в начало массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\sa \a prepend() inline PIDeque & prepend(T && e) {return push_front(std::move(e));} //! \~english Appends the given array `v` to the begin of the array. //! \~russian Добавляет массив `v` в начало массива. //! \~\details //! \~english Overloaded function. //! \~russian Перегруженая функция. //! \~\code //! PIDeque v{1, 2, 3}; //! v.prepend(PIDeque{4, 5}); //! piCout << v; // {4, 5, 1, 2, 3} //! \endcode //! \~\sa \a prepend() inline PIDeque & prepend(const PIDeque & v) {return push_front(v);} //! \~english Appends the given elements to the begin of the array. //! \~russian Добавляет элементы в начало массива. //! \~\details //! \~english Overloaded function. //! Appends the given elements from //! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). //! \~russian Перегруженая функция. //! Добавляет элементы из //! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). //! \~\sa \a append() inline PIDeque & prepend(std::initializer_list init_list) {return prepend(init_list);} //! \~english Remove one element from the end of the array. //! \~russian Удаляет один элемент с конца массива. //! \~\details //! \~english Deleting an element from the end is very fast //! and does not depend on the size of the array. //! \~russian Удаление элемента с конца выполняется очень быстро //! и не зависит от размера массива. //! \~\code //! PIDeque v{1, 2, 3}; //! v.pop_back(); //! piCout << v; // {1, 2} //! \endcode //! \~\sa \a pop_front(), \a take_back(), \a take_front() inline PIDeque & pop_back() { if (pid_size == 0) return *this; resize(pid_size - 1); return *this; } //! \~english Remove one element from the begining of the array. //! \~russian Удаляет один элемент с начала массива. //! \~\details //! \~english Removing an element from the beginning takes longer than from the end. //! This time is directly proportional to the size of the array. //! All iterators and references are invalidated. //! \~russian Удаление элемента с начала выполняется дольше, чем с конца. //! Это время прямопропорционально размеру массива. //! При удалении элемента все итераторы и указатели становятся нерабочими. //! \~\code //! PIDeque v{1, 2, 3}; //! v.pop_front(); //! piCout << v; // {2, 3} //! \endcode //! \~\sa \a pop_back(), \a take_back(), \a take_front() inline PIDeque & pop_front() { if (pid_size == 0) return *this; remove(0); return *this; } //! \~english Remove one element from the end of the array and return it. //! \~russian Удаляет один элемент с начала массива и возвращает его. //! \~\details //! \~\code //! PIDeque v{1, 2, 3}; //! piCout << v.take_back(); // 3 //! piCout << v; // {1, 2} //! \endcode //! \~\sa \a take_front(), \a pop_back(), \a pop_front() inline T take_back() { T e(back()); pop_back(); return e; } //! \~english Remove one element from the begining of the array and return it. //! \~russian Удаляет один элемент с конца массива и возвращает его. //! \~\details //! \~\code //! PIDeque v{1, 2, 3}; //! piCout << v.take_front(); // 1 //! piCout << v; // {2, 3} //! \endcode //! \~\sa \a take_front(), \a pop_back(), \a pop_front() inline T take_front() { T e(front()); pop_front(); return e; } //! \~english Returns an array converted to another type. //! \~russian Возвращает конвертированный в другой тип массив. //! \~\details //! \~\code //! PIDeque v{1.1, 2.5, 3.8}; //! PIDeque v2 = v.toType(); //! piCout << v2; // {1, 2, 3} //! \endcode //! \~\sa \a map() template inline PIDeque toType() const { PIDeque ret(pid_size); for (size_t i = 0; i < pid_size; ++i) { ret[i] = ST(pid_data[i + pid_start]); } return ret; } //! \~english Returns a new array with all elements //! that pass the test implemented by the provided function `test`. //! \~russian Возвращает новый массив со всеми элементами, //! прошедшими проверку, задаваемую в передаваемой функции `test`. //! \~\details //! \~\code //! PIDeque v{3, 2, 5, 2, 7}; //! PIDeque v2 = v.filter([](const int & i){return i > 2;}); //! piCout << v2; // {3, 5, 7} //! \endcode //! \~\sa \a map(), \a any(), \a every() inline PIDeque filter(std::function test) const { PIDeque ret; for (size_t i = pid_start; i < pid_start + pid_size; ++i) { if (test(pid_data[i])) ret << pid_data[i]; } return ret; } //! \~english Execute function `void f(const T & e)` for every element in array. //! \~russian Выполняет функцию `void f(const T & e)` для каждого элемента массива. //! \~\details //! \~russian Не позволяет изменять элементы массива. //! Для редактирования элементов используйте функцию вида `void f(T & e)`. //! \~english Does not allow changing array elements. //! To edit elements, use the function like `void f(T & e)` //! \~\code //! PIDeque v{1, 2, 3, 4, 5}; //! int s = 0; //! v.forEach([&s](const int & e){s += e;}); //! piCout << s; // 15 //! \endcode //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() inline void forEach(std::function f) const { for (size_t i = pid_start; i < pid_start + pid_size; ++i) { f(pid_data[i]); } } //! \~english Execute function `void f(T & e)` for every element in array. //! \~russian Выполняет функцию `void f(T & e)` для каждого элемента массива. //! \~\details //! \~english Overloaded function. //! Allows you to change the elements of the array. //! \~russian Перегруженая функция. //! Позволяет изменять элементы массива. //! \~\code //! PIDeque v{1, 2, 3, 4, 5}; //! v.forEach([](int & e){e++;}); //! piCout << v; // {2, 3, 4, 5, 6} //! \endcode //! \~\sa \a filter(), \a map(), \a reduce(), \a any(), \a every() inline PIDeque & forEach(std::function f) { for (size_t i = pid_start; i < pid_start + pid_size; ++i) { f(pid_data[i]); } return *this; } //! \~english Сreates a new array populated with the results //! of calling a provided function `ST f(const T & e)` on every element in the calling array. //! \~russian Создаёт новый массив с результатом вызова указанной функции //! `ST f(const T & e)` для каждого элемента массива. //! \~\details //! \~english Calls a provided function`ST f(const T & e)` //! once for each element in an array, in order, //! and constructs a new array from the results. //! \~russian Метод `map` вызывает переданную функцию `ST f(const T & e)` //! один раз для каждого элемента в порядке их появления //! и конструирует новый массив из результатов её вызова. //! \~\code //! PIDeque v{1, 2, 3}; //! PIStringList sl = v.map([](const int & i){return PIString::fromNumber(i);}); //! piCout << sl; {"1", "2", "3"} //! \endcode //! \~\sa \a forEach(), \a reduce() template inline PIDeque map(std::function f) const { PIDeque ret; ret.reserve(pid_size); for (size_t i = pid_start; i < pid_start + pid_size; ++i) { ret << f(pid_data[i]); } return ret; } //! \~english Applies the function `ST f(const T & e, const ST & acc)` //! to each element of the array (from left to right), returns one value. //! \~russian Применяет функцию `ST f(const T & e, const ST & acc)` //! к каждому элементу массива (слева-направо), возвращает одно значение. //! \~\details //! \~english The reduce() method performs the `f` function //! once for each element in the array. //! If the `initial` argument is passed when calling reduce(), //! then when the function `f` is called for the first time, //! the value of `acc` will be assigned to `initial`. //! If the array is empty, the value `initial` will be returned. //! \param f is a function like `ST f(const T & e, const ST & acc)`, //! executed for each element of the array. It takes two arguments: //! * **e** - current element of the array //! * **acc** - accumulator accumulating the value //! which this function returns after visiting the next element //! //! \param initial _optional_ Object used as the second argument //! when the `f` function is first called. //! \~russian Метод reduce() выполняет функцию `f` //! один раз для каждого элемента, присутствующего в массиве. //! Если при вызове reduce() передан аргумент `initial`, //! то при первом вызове функции `f` значение `acc` //! будет равным значению `initial`. //! Если массив пустой то будет возвращено значение `initial`. //! \param f Функция, вида `ST f(const T & e, const ST & acc)`, //! выполняющаяся для каждого элемента массива. //! Она принимает два аргумента: //! * **e** - текущий элемент массива //! * **acc** - аккумулятор, аккумулирующий значение //! которое возвращает эта функция после посещения очередного элемента //! //! \param initial _опциональный_ Объект, //! используемый в качестве второго аргумента при первом вызове функции `f`. //! //! \~\code //! PIDeque v{1, 2, 3, 4, 5}; //! int s = v.reduce([](const int & e, const int & acc){return e + acc;}); //! piCout << s; // 15 //! \endcode //! \~\sa \a forEach(), \a map() template inline ST reduce(std::function f, const ST & initial = ST()) const { ST ret(initial); for (size_t i = pid_start; i < pid_start + pid_size; ++i) { ret = f(pid_data[i], ret); } return ret; } //! \~english Changes the dimension of the array, creates a two-dimensional array from a one-dimensional array. //! \~russian Изменяет размерность массива, из одномерного массива создает двухмерный. //! \~\details //! \~russian //! \param rows размер внешнего массива //! \param cols размер внутренних массивов //! \param order порядок обхода исходного массива, задаётся с помощью \a ReshapeOrder //! \~english //! \param rows size external array //! \param cols size internal arrays //! \param order the order of traversing the source array is set using \a ReshapeOrder //! \~\code //! PIDeque v{1, 2, 3, 4}; //! PIDeque> m1 = v.reshape(2,2); //! piCout << m1; // {{1, 2}, {3, 4}} //! PIDeque> m2 = v.reshape(2,2, ReshapeByColumn); //! piCout << m2; // {{1, 3}, {2, 4}} //! \endcode //! \~\sa \a map(), \a reduce(), \a flatten() inline PIDeque> reshape(size_t rows, size_t cols, ReshapeOrder order = ReshapeByRow) const { PIDeque> ret; if (isEmpty()) return ret; #ifndef NDEBUG if (rows*cols != pid_size) { printf("error with PIDeque<%s>::reshape\n", __PIP_TYPENAME__(T)); } #endif assert(rows*cols == pid_size); ret.resize(rows); if (order == ReshapeByRow) { for (size_t r = 0; r < rows; r++) { ret[r] = PIDeque(&(pid_data[r*cols]), cols); } } if (order == ReshapeByColumn) { for (size_t r = 0; r < rows; r++) { ret[r].resize(cols); for (size_t c = 0; c < cols; c++) { ret[r][c] = pid_data[c*rows + r]; } } } return ret; } //! \~english Changes the dimension of the array, creates a one-dimensional array from a two-dimensional array. //! \~russian Изменяет размерность массива, из двухмерный массива создает одномерный. //! \~\details //! \~russian Делает массив плоским. //! Порядок обхода исходного массива задаётся с помощью \a ReshapeOrder. //! \~english Makes the array flat. //! Еhe order of traversing the source array is set using \a ReshapeOrder. //! \~\code //! PIDeque v{1, 2, 3, 4, 5, 6}; //! PIDeque> xv = v.reshape(3,2); //! piCout << xv; // {{1, 2}, {3, 4}, {5, 6}} //! piCout << xv.flatten(); // {1, 2, 3, 4, 5, 6} //! \endcode //! \~\sa \a map(), \a reduce(), \a reshape() template>::value , int>::type = 0> inline PIDeque flatten(ReshapeOrder order = ReshapeByRow) const { PIDeque ret; if (isEmpty()) return ret; size_t rows = size(); size_t cols = at(0).size(); ret.reserve(rows * cols); if (order == ReshapeByRow) { for (size_t r = 0; r < rows; r++) { ret.append(at(r)); } } if (order == ReshapeByColumn) { for (size_t c = 0; c < cols; c++) { for (size_t r = 0; r < rows; r++) { ret << at(r)[c]; } } } ret.resize(rows * cols); return ret; } //! \~english Changes the dimension of the two-dimensional array. //! \~russian Изменяет размерность двухмерного массива. //! \~\details //! \~russian //! \param rows размер внешнего массива //! \param cols размер внутренних массивов //! \param order порядок обхода исходного массива, задаётся с помощью \a ReshapeOrder //! \~english //! \param rows size external array //! \param cols size internal arrays //! \param order the order of traversing the source array is set using \a ReshapeOrder //! \~\code //! PIDeque v{1, 2, 3, 4, 5, 6}; //! PIDeque> xv = v.reshape(3,2); //! piCout << xv; // {{1, 2}, {3, 4}, {5, 6}} //! piCout << xv.reshape(2,3); // {{1, 2, 3}, {4, 5, 6}} //! \endcode //! \~\sa \a map(), \a reduce(), \a reshape() template>::value , int>::type = 0> inline PIDeque> reshape(size_t rows, size_t cols, ReshapeOrder order = ReshapeByRow) const { PIDeque fl = flatten(); return fl.reshape(rows, cols, order); } private: inline void _reset() {pid_size = pid_rsize = pid_start = 0; pid_data = 0;} inline size_t asize(ssize_t s) { if (s <= 0) return 0; if (pid_rsize + pid_rsize >= size_t(s) && pid_rsize < size_t(s)) { return pid_rsize + pid_rsize; } ssize_t t = 0, s_ = s - 1; while (s_ >> t) { ++t; } return (1 << t); } template::value , int>::type = 0> inline void newT(T * dst, const T * src, size_t s) { PIINTROSPECTION_CONTAINER_USED(T, s) for (size_t i = 0; i < s; ++i) elementNew(dst + i, src[i]); } template::value , int>::type = 0> inline void newT(T * dst, const T * src, size_t s) { PIINTROSPECTION_CONTAINER_USED(T, s) memcpy((void*)(dst), (const void*)(src), s * sizeof(T)); } template::value , int>::type = 0> inline void deleteT(T * d, size_t sz) { PIINTROSPECTION_CONTAINER_UNUSED(T, sz) if ((uchar*)d != 0) { for (size_t i = 0; i < sz; ++i) { elementDelete(d[i]); } } } template::value , int>::type = 0> inline void deleteT(T * d, size_t sz) { PIINTROSPECTION_CONTAINER_UNUSED(T, sz) } template::value , int>::type = 0> inline void elementNew(T * to, const T & from) {new(to)T(from);} template::value , int>::type = 0> inline void elementNew(T * to, T && from) {new(to)T(std::move(from));} template::value , int>::type = 0> inline void elementNew(T1 * to, const T & from) {(*to) = from;} template::value , int>::type = 0> inline void elementNew(T * to, T && from) {(*to) = std::move(from);} template::value , int>::type = 0> inline void elementDelete(T & from) {from.~T();} template::value , int>::type = 0> inline void elementDelete(T & from) {} inline void dealloc() { if ((uchar*)pid_data != 0) free((uchar*)pid_data); pid_data = 0; } inline void checkMove() { if (pid_size >= 4) { if (pid_size < pid_rsize / 6) { if (pid_start < ssize_t(pid_size + pid_size) || pid_start > (ssize_t(pid_rsize) - ssize_t(pid_size) - ssize_t(pid_size))) { ssize_t ns = (pid_rsize - pid_size) / 2; if (pid_start != ns) { memmove((void*)(pid_data + ns), (const void*)(pid_data + pid_start), pid_size * sizeof(T)); pid_start = ns; } } } } else { ssize_t ns = (pid_rsize - pid_size) / 2; if (pid_start != ns) { memmove((void*)(pid_data + ns), (const void*)(pid_data + pid_start), pid_size * sizeof(T)); pid_start = ns; } } } inline void alloc_forward(size_t new_size) { // direction == true -> alloc forward if (pid_start + new_size <= pid_rsize) { pid_size = new_size; checkMove(); return; } pid_size = new_size; size_t as = asize(pid_start + new_size); if (as != pid_rsize) { PIINTROSPECTION_CONTAINER_ALLOC(T, (as-pid_rsize)) T * p_d = (T*)(realloc((void*)(pid_data), as*sizeof(T))); #ifndef NDEBUG if (!p_d) { printf("error with PIDeque<%s>::alloc\n", __PIP_TYPENAME__(T)); } #endif assert(p_d); pid_data = p_d; pid_rsize = as; } } inline void alloc_backward(size_t new_size, ssize_t start_offset = 0) { //alloc backward size_t as; if (pid_start + start_offset < 0) { as = asize(pid_rsize - start_offset); } else { as = pid_rsize; } if (as > pid_rsize) { T * td = (T*)(malloc(as * sizeof(T))); ssize_t ns = pid_start + as - pid_rsize; PIINTROSPECTION_CONTAINER_ALLOC(T, (as-pid_rsize)) if (pid_rsize > 0 && pid_data != 0) { memcpy((void*)(td + ns), (const void*)(pid_data + pid_start), pid_size * sizeof(T)); dealloc(); } pid_data = td; pid_rsize = as; pid_start = ns; } pid_start += start_offset; pid_size = new_size; checkMove(); } T * pid_data; size_t pid_size, pid_rsize; ssize_t pid_start; }; #ifdef PIP_STD_IOSTREAM //! \~english Output operator to [std::ostream](https://en.cppreference.com/w/cpp/io/basic_ostream). //! \~russian Оператор вывода в [std::ostream](https://ru.cppreference.com/w/cpp/io/basic_ostream). template inline std::ostream & operator <<(std::ostream & s, const PIDeque & v) { s << "{"; for (size_t i = 0; i < v.size(); ++i) { s << v[i]; if (i < v.size() - 1) s << ", "; } s << "}"; return s; } #endif //! \relatesalso PICout //! \~english Output operator to \a PICout //! \~russian Оператор вывода в \a PICout template inline PICout operator <<(PICout s, const PIDeque & v) { s.space(); s.setControl(0, true); s << "{"; for (size_t i = 0; i < v.size(); ++i) { s << v[i]; if (i < v.size() - 1) s << ", "; } s << "}"; s.restoreControl(); return s; } template inline void piSwap(PIDeque & f, PIDeque & s) {f.swap(s);} #endif // PIDEQUE_H