//! \addtogroup Containers //! \{ //! \file pivector.h //! \brief //! \~english Declares \a PIVector //! \~russian Объявление \a PIVector //! \~\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 Sequence linear container aka dynamic size 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 PIVECTOR_H #define PIVECTOR_H #include "picontainers.h" //! \addtogroup Containers //! \{ //! \class PIVector //! \brief //! \~english Sequence 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 vector may be passed to any function //! that expects a pointer to an element of an array. //! //! The storage of the vector is handled automatically, //! being expanded and contracted as needed. //! Vectors usually occupy more space than static arrays, //! because more memory is allocated to handle future growth. //! This way a vector 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 vectors is as follows: //! - Random access - constant 𝓞(1) //! - Insertion or removal of elements at the end - amortized constant 𝓞(1) //! - Insertion or removal of elements - linear in the distance to the end of the vector 𝓞(n) //! //! \~russian //! Элементы хранятся непрерывно, а значит доступны не только через итераторы, //! но и с помощью смещений для обычных указателей на элементы. //! Это означает, что указатель на элемент вектора может передаваться в любую функцию, //! ожидающую указатель на элемент массива. //! //! Память вектора обрабатывается автоматически, //! расширяясь и сжимаясь по мере необходимости. //! Векторы обычно занимают больше места, чем статические массивы, //! поскольку больше памяти выделяется для обработки будущего роста. //! Таким образом, память для вектора требуется выделять //! не при каждой вставке элемента, //! а только после исчерпания дополнительной памяти. //! Общий объём выделенной памяти можно получить с помощью функции \a capacity(). //! //! Выделение памяти обычно является дорогостоящей операцией //! с точки зрения производительности. //! Функцию \a reserve() можно использовать для исключения выделения памяти, //! если количество элементов известно заранее. //! //! Сложность (эффективность) обычных операций над векторами следующая: //! - Произвольный доступ — постоянная 𝓞(1) //! - Вставка и удаление элементов в конце — амортизированная постоянная 𝓞(1) //! - Вставка и удаление элементов — линейная по расстоянию до конца вектора 𝓞(n) //! //! \~\sa \a PIDeueue, \a PIMap template class PIVector { public: //! \~\brief //! \~english Constructs an empty vector. //! \~russian Создает пустой массив. inline PIVector(): piv_data(0), piv_size(0), piv_rsize(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) } //! \~\brief //! \~english Contructs vector from raw `data`. //! This constructor reserve `size` and copy from `data` pointer. //! \~russian Создает массив из указателя на данные `data` и размер `size`. //! То есть выделяет память для `size` элементов и копирует данные из указателя `data`. inline PIVector(const T * data, size_t size): piv_data(0), piv_size(0), piv_rsize(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) alloc(size); newT(piv_data, data, piv_size); } //! \~\brief //! \~english Copy constructor. //! \~russian Копирующий конструктор. inline PIVector(const PIVector & v): piv_data(0), piv_size(0), piv_rsize(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) alloc(v.piv_size); newT(piv_data, v.piv_data, piv_size); } //! \~\brief //! \~english Contructs vector 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 //! PIVector v{1,2,3}; //! piCout << v; // {1, 2, 3} //! \endcode inline PIVector(std::initializer_list init_list): piv_data(0), piv_size(0), piv_rsize(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) alloc(init_list.size()); newT(piv_data, init_list.begin(), init_list.size()); } //! \~\brief //! \~english Contructs vector with size `size` filled elements `e`. //! \~russian Создает массив из `size` элементов заполненных `e`. inline PIVector(size_t size, const T & e = T()): piv_data(0), piv_size(0), piv_rsize(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) resize(size, e); } //! \~\brief //! \~english Contructs vector 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 //! PIVector v(5, [](size_t i){return i*2;}); //! piCout << v; // {0, 2, 4, 6, 8} //! \endcode inline PIVector(size_t size, std::function f): piv_data(0), piv_size(0), piv_rsize(0) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) resize(size, f); } //! \~\brief //! \~english Move constructor. //! \~russian Перемещающий конструктор. inline PIVector(PIVector && v): piv_data(v.piv_data), piv_size(v.piv_size), piv_rsize(v.piv_rsize) { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) v._reset(); } inline virtual ~PIVector() { PIINTROSPECTION_CONTAINER_DELETE(T) PIINTROSPECTION_CONTAINER_FREE(T, (piv_rsize)) deleteT(piv_data, piv_size); dealloc(); _reset(); } //! \~\brief //! \~english Assign operator. //! \~russian Оператор присваивания. inline PIVector & operator =(const PIVector & v) { if (this == &v) return *this; clear(); deleteT(piv_data, piv_size); alloc(v.piv_size); newT(piv_data, v.piv_data, piv_size); return *this; } //! \~\brief //! \~english Assign move operator. //! \~russian Оператор перемещающего присваивания. inline PIVector & operator =(PIVector && v) { swap(v); return *this; } //! \~\brief //! \~english Reshape order enum for \a reshape function. //! \~russian Порядок обхода для функции изменения размерности \a reshape. enum ReshapeOrder { byRow, byColumn }; class iterator { friend class PIVector; private: inline iterator(PIVector * v, size_t p): parent(v), pos(p) {} PIVector * parent; size_t pos; public: inline iterator(): parent(0), pos(0) {} inline T & operator *() {return (*parent)[pos];} inline const T & operator *() const {return (*parent)[pos];} inline void operator ++() {++pos;} inline void operator ++(int) {++pos;} inline void operator --() {--pos;} inline void operator --(int) {--pos;} inline bool operator ==(const iterator & it) const {return (pos == it.pos);} inline bool operator !=(const iterator & it) const {return (pos != it.pos);} }; class const_iterator { friend class PIVector; private: inline const_iterator(const PIVector * v, size_t p): parent(v), pos(p) {} const PIVector * parent; size_t pos; public: inline const_iterator(): parent(0), pos(0) {} inline const T & operator *() const {return (*parent)[pos];} inline void operator ++() {++pos;} inline void operator ++(int) {++pos;} inline void operator --() {--pos;} inline void operator --(int) {--pos;} inline bool operator ==(const const_iterator & it) const {return (pos == it.pos);} inline bool operator !=(const const_iterator & it) const {return (pos != it.pos);} }; class reverse_iterator { friend class PIVector; private: inline reverse_iterator(PIVector * v, size_t p): parent(v), pos(p) {} PIVector * parent; size_t pos; public: inline reverse_iterator(): parent(0), pos(0) {} inline T & operator *() {return (*parent)[pos];} inline const T & operator *() const {return (*parent)[pos];} inline void operator ++() {--pos;} inline void operator ++(int) {--pos;} inline void operator --() {++pos;} inline void operator --(int) {++pos;} inline bool operator ==(const reverse_iterator & it) const {return (pos == it.pos);} inline bool operator !=(const reverse_iterator & it) const {return (pos != it.pos);} }; class const_reverse_iterator { friend class PIVector; private: inline const_reverse_iterator(const PIVector * v, size_t p): parent(v), pos(p) {} const PIVector * parent; size_t pos; public: inline const_reverse_iterator(): parent(0), pos(0) {} inline const T & operator *() const {return (*parent)[pos];} inline void operator ++() {--pos;} inline void operator ++(int) {--pos;} inline void operator --() {++pos;} inline void operator --(int) {++pos;} 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);} }; //! \~\brief //! \~english Iterator to the first element. //! \~russian Итератор на первый элемент. //! \~\details ![begin, end](doc/images/pivector_begin.png) //! //! \~english If the vector 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);} //! \~\brief //! \~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, piv_size);} inline const_iterator begin() const {return const_iterator(this, 0);} inline const_iterator end() const {return const_iterator(this, piv_size);} //! \~\brief //! \~english Returns a reverse iterator to the first element of the reversed vector. //! \~russian Обратный итератор на первый элемент. //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) //! //! \~english It corresponds to the last element of the non-reversed vector. //! If the vector 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, piv_size - 1);} //! \~\brief //! \~english Returns a reverse iterator to the element //! following the last element of the reversed vector. //! \~russian Обратный итератор на элемент, следующий за последним элементом. //! \~\details ![rbegin, rend](doc/images/pivector_rbegin.png) //! //! \~english It corresponds to the element preceding the first element of the non-reversed vector. //! 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, piv_size - 1);} inline const_reverse_iterator rend() const {return const_reverse_iterator(this, -1);} //! \~\brief //! \~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 piv_size;} //! \~\brief //! \~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 piv_size;} //! \~\brief //! \~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 piv_size;} //! \~\brief //! \~english Number of elements that the container has currently allocated space for. //! \~russian Количество элементов, для которого сейчас выделена память контейнером. //! \~\sa \a size \a size_s, \a isEmpty, \a isNotEmpty, \a resize, \a reserve inline size_t capacity() const {return piv_rsize;} //! \~\brief //! \~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 (piv_size == 0);} //! \~\brief //! \~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 (piv_size > 0);} //! \~\brief //! \~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 //! PIVector 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 etries, \a forEach inline bool any(std::function test) const { for (size_t i = 0; i < piv_size; ++i) { if (test(piv_data[i])) return true; } return false; } //! \~\brief //! \~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 //! PIVector 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 (size_t i = 0; i < piv_size; ++i) { if (!test(piv_data[i])) return false; } return true; } //! \brief //! \~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 //! PIVector 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 piv_data[index];} inline const T & operator [](size_t index) const {return piv_data[index];} //! \brief //! \~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 piv_data[index];} //! \brief //! \~english Last element. //! \~russian Последний элемент массива. //! \~\details //! \~english Returns a reference to the last item in the vector. //! This function assumes that the vector isn't empty. //! Otherwise will be undefined behavior. //! \~russian Возвращает ссылку на последний элемент в массиве. //! Эта функция предполагает, что массив не пустой. //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. inline T & back() {return piv_data[piv_size - 1];} inline const T & back() const {return piv_data[piv_size - 1];} //! \brief //! \~english Last element. //! \~russian Первый элемент массива. //! \~\details //! \~english Returns a reference to the last item in the vector. //! This function assumes that the vector isn't empty. //! Otherwise will be undefined behavior. //! \~russian Возвращает ссылку на пенрвый элемент в массиве. //! Эта функция предполагает, что массив не пустой. //! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти. inline T & front() {return piv_data[0];} inline const T & front() const {return piv_data[0];} //! \brief //! \~english Compare operator with vector `t`. //! \~russian Оператор сравнения с массивом `t`. inline bool operator ==(const PIVector & t) const { if (piv_size != t.piv_size) { return false; } for (size_t i = 0; i < piv_size; ++i) { if (t[i] != piv_data[i]) { return false; } } return true; } //! \brief //! \~english Compare operator with vector `t`. //! \~russian Оператор сравнения с массивом `t`. inline bool operator !=(const PIVector & t) const {return !(*this == t);} //! \~\brief //! \~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 //! PIVector 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 etries, \a forEach inline bool contains(const T & e, ssize_t start = 0) const { if (start < 0) { start = piv_size + start; if (start < 0) start = 0; } for (size_t i = start; i < piv_size; ++i) { if (e == piv_data[i]) return true; } return false; } //! \~\brief //! \~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 //! PIVector 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, ssize_t start = 0) const { int ec = 0; if (start < 0) { start = piv_size + start; if (start < 0) start = 0; } for (size_t i = start; i < piv_size; ++i) { if (e == piv_data[i]) ++ec; } return ec; } //! \~\brief //! \~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, ssize_t start = 0) const { int ec = 0; if (start < 0) { start = piv_size + start; if (start < 0) start = 0; } for (size_t i = start; i < piv_size; ++i) { if (test(piv_data[i])) ++ec; } return ec; } //! \~\brief //! \~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 //! PIVector 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, ssize_t start = 0) const { if (start < 0) { start = piv_size + start; if (start < 0) start = 0; } for (size_t i = start; i < piv_size; ++i) { if (e == piv_data[i]) return i; } return -1; } //! \~\brief //! \~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 //! PIVector 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, ssize_t start = 0) const { if (start < 0) { start = piv_size + start; if (start < 0) start = 0; } for (size_t i = start; i < piv_size; ++i) { if (test(piv_data[i])) return i; } return -1; } //! \~\brief //! \~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 //! PIVector 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 = piv_size - 1; if (start < 0) start = piv_size + start; for (ssize_t i = start; i >= 0; --i) { if (e == piv_data[i]) return i; } return -1; } //! \~\brief //! \~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 = piv_size - 1; if (start < 0) start = piv_size + start; for (ssize_t i = start; i >= 0; --i) { if (test(piv_data[i])) return i; } return -1; } //! \~\brief //! \~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 //! PIVector v{2, 5, 9, 2}; //! int a[2] = {12, 13}; //! memcpy(vec.data(1), carr, 2 * sizeof(int)); //! piCout << v; // 2, 12, 13, 2 //! \endcode inline T * data(size_t index = 0) {return &(piv_data[index]);} //! \~\brief //! \~english Read only 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 //! PIVector 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 &(piv_data[index]);} PIVector getRange(size_t index, size_t count) const { if (index >= piv_size || count == 0) return PIVector(); if (index + count > piv_size) count = piv_size - index; return PIVector(&(piv_data[index]), count); } template::value , int>::type = 0> inline PIVector & clear() { resize(0); return *this; } template::value , int>::type = 0> inline PIVector & clear() { PIINTROSPECTION_CONTAINER_UNUSED(T, piv_size) piv_size = 0; return *this; } inline PIVector & fill(const T & f = T()) { deleteT(piv_data, piv_size); PIINTROSPECTION_CONTAINER_USED(T, piv_size) for (size_t i = 0; i < piv_size; ++i) { elementNew(piv_data + i, f); } return *this; } inline PIVector & fill(std::function f) { deleteT(piv_data, piv_size); PIINTROSPECTION_CONTAINER_USED(T, piv_size) for (size_t i = 0; i < piv_size; ++i) { elementNew(piv_data + i, f(i)); } return *this; } inline PIVector & assign(const T & f = T()) {return fill(f);} template::value , int>::type = 0> inline PIVector & assign(size_t new_size, const T & f) { resize(new_size); return fill(f); } template::value , int>::type = 0> inline PIVector & assign(size_t new_size, const T & f) { _resizeRaw(new_size); return fill(f); } inline PIVector & resize(size_t new_size, const T & f = T()) { if (new_size < piv_size) { T * de = &(piv_data[new_size]); deleteT(de, piv_size - new_size); piv_size = new_size; } if (new_size > piv_size) { size_t os = piv_size; alloc(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size-os)) for (size_t i = os; i < new_size; ++i) { elementNew(piv_data + i, f); } } return *this; } inline PIVector & resize(size_t new_size, std::function f) { if (new_size < piv_size) { T * de = &(piv_data[new_size]); deleteT(de, piv_size - new_size); piv_size = new_size; } if (new_size > piv_size) { size_t os = piv_size; alloc(new_size); PIINTROSPECTION_CONTAINER_USED(T, (new_size-os)) for (size_t i = os; i < new_size; ++i) { elementNew(piv_data + i, f(i)); } } return *this; } template::value , int>::type = 0> inline PIVector & _resizeRaw(size_t new_size) { if (new_size > piv_size) { PIINTROSPECTION_CONTAINER_USED(T, (new_size-piv_size)); } if (new_size < piv_size) { PIINTROSPECTION_CONTAINER_UNUSED(T, (piv_size-new_size)); } alloc(new_size); return *this; } inline void _copyRaw(T * dst, const T * src, size_t size) { newT(dst, src, size); } inline PIVector & reserve(size_t new_size) { if (new_size <= piv_rsize) return *this; size_t os = piv_size; alloc(new_size); piv_size = os; return *this; } inline PIVector & insert(size_t index, const T & e = T()) { alloc(piv_size + 1); if (index < piv_size - 1) { size_t os = piv_size - index - 1; memmove((void*)(&(piv_data[index + 1])), (const void*)(&(piv_data[index])), os * sizeof(T)); } PIINTROSPECTION_CONTAINER_USED(T, 1) elementNew(piv_data + index, e); return *this; } inline PIVector & insert(size_t index, T && e) { alloc(piv_size + 1); if (index < piv_size - 1) { size_t os = piv_size - index - 1; memmove((void*)(&(piv_data[index + 1])), (const void*)(&(piv_data[index])), os * sizeof(T)); } PIINTROSPECTION_CONTAINER_USED(T, 1) elementNew(piv_data + index, std::move(e)); return *this; } inline PIVector & insert(size_t index, const PIVector & v) { if (v.isEmpty()) return *this; assert(&v != this); ssize_t os = piv_size - index; alloc(piv_size + v.piv_size); if (os > 0) { memmove((void*)(&(piv_data[index + v.piv_size])), (const void*)(&(piv_data[index])), os * sizeof(T)); } newT(piv_data + index, v.piv_data, v.piv_size); return *this; } inline PIVector & remove(size_t index, size_t count = 1) { if (count == 0) return *this; if (index + count >= piv_size) { resize(index); return *this; } size_t os = piv_size - index - count; deleteT(&(piv_data[index]), count); memmove((void*)(&(piv_data[index])), (const void*)(&(piv_data[index + count])), os * sizeof(T)); piv_size -= count; return *this; } inline void swap(PIVector & v) { piSwap(piv_data, v.piv_data); piSwap(piv_size, v.piv_size); piSwap(piv_rsize, v.piv_rsize); } typedef int (*CompareFunc)(const T * , const T * ); static int compare_func(const T * t0, const T * t1) {return (*t0) < (*t1) ? -1 : ((*t0) == (*t1) ? 0 : 1);} inline PIVector & sort(CompareFunc compare = compare_func) { piqsort(piv_data, piv_size, sizeof(T), (int(*)(const void * , const void * ))compare); return *this; } inline PIVector & enlarge(llong piv_size) { llong ns = size_s() + piv_size; if (ns <= 0) clear(); else resize(size_t(ns)); return *this; } /*! \brief Remove no more than one element equal "v" and return reference to vector * \details Example: \snippet picontainers.cpp PIVector::removeOne * \sa \a remove(), \a removeAll() */ inline PIVector & removeOne(const T & e) { for (size_t i = 0; i < piv_size; ++i) { if (piv_data[i] == e) { remove(i); return *this; } } return *this; } inline PIVector & removeAll(const T & e) { for (ssize_t i = 0; i < ssize_t(piv_size); ++i) { if (piv_data[i] == e) { remove(i); --i; } } return *this; } inline PIVector & removeWhere(std::function test) { for (ssize_t i = 0; i < ssize_t(piv_size); ++i) { if (test(piv_data[i])) { remove(i); --i; } } return *this; } inline PIVector & push_back(const T & e) { alloc(piv_size + 1); PIINTROSPECTION_CONTAINER_USED(T, 1); elementNew(piv_data + piv_size - 1, e); return *this; } inline PIVector & push_back(T && e) { alloc(piv_size + 1); PIINTROSPECTION_CONTAINER_USED(T, 1); elementNew(piv_data + piv_size - 1, std::move(e)); return *this; } inline PIVector & push_back(std::initializer_list init_list) { size_t ps = piv_size; alloc(piv_size + init_list.size()); newT(piv_data + ps, init_list.begin(), init_list.size()); return *this; } inline PIVector & push_back(const PIVector & v) { assert(&v != this); size_t ps = piv_size; alloc(piv_size + v.piv_size); newT(piv_data + ps, v.piv_data, v.piv_size); return *this; } inline PIVector & append(const T & e) {return push_back(e);} inline PIVector & append(T && e) {return push_back(std::move(e));} inline PIVector & append(std::initializer_list init_list) {return push_back(init_list);} inline PIVector & append(const PIVector & v) {return push_back(v);} inline PIVector & operator <<(const T & e) {return push_back(e);} inline PIVector & operator <<(T && e) {return push_back(std::move(e));} inline PIVector & operator <<(const PIVector & v) {return push_back(v);} inline PIVector & push_front(const T & e) {insert(0, e); return *this;} inline PIVector & push_front(T && e) {insert(0, std::move(e)); return *this;} inline PIVector & push_front(const PIVector & v) {insert(0, v); return *this;} inline PIVector & prepend(const T & e) {return push_front(e);} inline PIVector & prepend(T && e) {return push_front(std::move(e));} inline PIVector & prepend(const PIVector & v) {return push_front(v);} inline PIVector & pop_back() { if (piv_size == 0) return *this; resize(piv_size - 1); return *this; } inline PIVector & pop_front() { if (piv_size == 0) return *this; remove(0); return *this; } inline T take_back() {T e(back()); pop_back(); return e;} inline T take_front() {T e(front()); pop_front(); return e;} template PIVector toType() const { PIVector ret(piv_size); for (size_t i = 0; i < piv_size; ++i) { ret[i] = ST(piv_data[i]); } return ret; } const PIVector & forEach(std::function f) const { for (size_t i = 0; i < piv_size; ++i) { f(piv_data[i]); } return *this; } PIVector copyForEach(std::function f) const { PIVector ret; ret.reserve(piv_size); for (size_t i = 0; i < piv_size; ++i) { ret << f(piv_data[i]); } return ret; } PIVector & forEachInplace(std::function f) { for (size_t i = 0; i < piv_size; ++i) { piv_data[i] = f(piv_data[i]); } return *this; } template PIVector map(std::function f) const { PIVector ret; ret.reserve(piv_size); for (size_t i = 0; i < piv_size; ++i) { ret << f(piv_data[i]); } return ret; } template PIVector toType(std::function f) const {return map(f);} template ST reduce(std::function f, const ST & initial = ST()) const { ST ret(initial); for (size_t i = 0; i < piv_size; ++i) { ret = f(piv_data[i], ret); } return ret; } inline PIVector> reshape(size_t rows, size_t cols, ReshapeOrder order = byRow) const { PIVector> ret; if (isEmpty()) return ret; assert(rows*cols == piv_size); ret.resize(rows); if (order == byRow) { for (size_t r = 0; r < rows; r++) { ret[r] = PIVector(&(piv_data[r*cols]), cols); } } if (order == byColumn) { for (size_t r = 0; r < rows; r++) { ret[r].resize(cols); for (size_t c = 0; c < cols; c++) { ret[r][c] = piv_data[c*rows + r]; } } } return ret; } template>::value , int>::type = 0> inline PIVector reshape(ReshapeOrder order = byRow) const { PIVector ret; if (isEmpty()) return ret; size_t rows = size(); size_t cols = at(0).size(); ret.reserve(rows * cols); if (order == byRow) { for (size_t r = 0; r < rows; r++) { ret.append(at(r)); } } if (order == byColumn) { 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; } private: inline void _reset() {piv_size = piv_rsize = 0; piv_data = 0;} inline size_t asize(size_t s) { if (s == 0) return 0; if (piv_rsize + piv_rsize >= s && piv_rsize < s) { return piv_rsize + piv_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*)piv_data != 0) free((uchar*)piv_data); piv_data = 0; } inline void alloc(size_t new_size) { if (new_size <= piv_rsize) { piv_size = new_size; return; } piv_size = new_size; size_t as = asize(new_size); if (as == piv_rsize) return; PIINTROSPECTION_CONTAINER_ALLOC(T, (as-piv_rsize)) T * p_d = (T*)(realloc((void*)(piv_data), as*sizeof(T))); assert(p_d); piv_data = p_d; piv_rsize = as; } T * piv_data; size_t piv_size, piv_rsize; }; #ifdef PIP_STD_IOSTREAM template inline std::ostream & operator <<(std::ostream & s, const PIVector & v) { s << "{"; for (size_t i = 0; i < v.size(); ++i) { s << v[i]; if (i < v.size() - 1) s << ", "; } s << "}"; return s; } #endif template inline PICout operator <<(PICout s, const PIVector & 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(PIVector & f, PIVector & s) {f.swap(s);} #endif // PIVECTOR_H