Vector front c описание
Обновлено: 05.07.2024
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 capacity() function. Extra memory can be returned to the system via a call to shrink_to_fit() . (since C++11)
Reallocations are usually costly operations in terms of performance. The 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)
Member functions of std::vector are constexpr : it is possible to create and use std::vector objects in the evaluation of a constant expression.
However, std::vector objects generally cannot be constexpr , because any dynamically allocated storage must be released in the same evaluation of constant expression.
Требования
Заголовок:<cliext/vector>
Пространство имен: cliext
Синтаксис
Параметры
Значение
Тип элемента в управляемой последовательности.
Интерфейсы
Интерфейс | Описание |
---|---|
ICloneable | Дублировать объект. |
IEnumerable | Последовательное упорядочение элементов. |
ICollection | Поддержка группы элементов. |
IEnumerable<T> | Последовательность через типизированные элементы. |
ICollection<T> | Поддержание группы типизированных элементов. |
IList<T> | Поддерживать упорядоченную группу типизированных элементов. |
Значение<IVector> | Поддержание универсального контейнера. |
Remarks
Объект выделяет и освобождает хранилище для последовательности, которая управляется с помощью сохраненного массива элементов value , который растет по запросу. Рост происходит таким образом, что стоимость добавления нового элемента приводит к амортизации постоянного времени. Иными словами, затраты на добавление элементов в конце не увеличиваются в среднем, так как длина управляемой последовательности становится больше. Таким же, вектор является хорошим кандидатом для базового контейнера для стека классов шаблонов (STL/CLR).
vector Поддерживает итераторы произвольного доступа, что означает, что вы можете ссылаться на элемент непосредственно в своем числовом положении, считая от нуля для первого (переднего) элемента до size() - 1 последнего (Back) элемента. Это также означает, что вектор является хорошим кандидатом для базового контейнера класса шаблона priority_queue (STL/CLR).
Итератор вектора сохраняет указатель на связанный с ним объект Vector вместе с сдвигом элемента, который он определяет. Итераторы можно использовать только со связанными объектами контейнера. Сдвиг элемента Vector совпадает с его позицией.
Вставка или стирание элементов может изменить значение элемента, хранящееся в заданной позиции, поэтому значение, назначенное итератором, также может измениться. (Чтобы создать отверстие перед вставкой или заполнить отверстие после стирания, контейнеру может потребоваться скопировать элементы вверх или вниз.) Тем не менее, итератор вектора остается действительным до тех пор, пока его смещение находится в диапазоне [0, size()] . Кроме того, допустимый итератор остается недереференкабленым — вы можете использовать его для доступа к значению элемента, которое он определяет, или изменять его значение, если его смещение не равно size() .
При стирании или удалении элемента вызывается деструктор для его сохраненного значения. При уничтожении контейнера удаляются все элементы. Таким образом, контейнер, тип элемента которого является ссылочным классом, гарантирует, что контейнер не будет находиться ни в одной из элементов. Однако обратите внимание, что контейнер дескрипторов не уничтожает свои элементы.
Contents
[edit] Template parameters
T | - | The type of the elements.
[edit] SpecializationsThe standard library provides a specialization of std::vector for the type bool , which may be optimized for space efficiency. Vectors are sequence containers representing arrays that can change in size. Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container. Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container. Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size). Libraries can implement different strategies for growth to balance between memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing intervals of size so that the insertion of individual elements at the end of the vector can be provided with amortized constant time complexity (see push_back). Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way. Compared to the other dynamic sequence containers (deques, lists and forward_lists), vectors are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements from its end. For operations that involve inserting or removing elements at positions other than the end, they perform worse than the others, and have less consistent iterators and references than lists and forward_lists. Returns a reference to the first element in the vector. Unlike member vector::begin, which returns an iterator to this same element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior. ParametersReturn valueA reference to the first element in the vector container. If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference. Member types reference and const_reference are the reference types to the elements of the container (see vector member types). Класс шаблона описывает объект, управляющий последовательностью элементов различной длины с произвольным доступом. Контейнер используется vector для управления последовательностью элементов в виде непрерывного блока хранилища. Блок реализуется как массив, который растет по запросу. В описании ниже GValue то же самое, что и значение , если только второй не является ссылочным типом, в этом случае — Value^ . Объявления
Читайте также:
|