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.
T must meet the requirements of CopyAssignable and CopyConstructible . (until C++11)
The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable , but many member functions impose stricter requirements. (since C++11)
(until C++17)
The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of Erasable , but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the allocator completeness requirements. (since C++17)

[edit] Specializations

The 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.

Parameters

Return value

A 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^ .

Объявления

Определение типа Описание
vector::const_iterator (STL/CLR) Тип постоянного итератора для управляемой последовательности.
vector::const_reference (STL/CLR) Тип постоянной ссылки на элемент.
vector::const_reverse_iterator (STL/CLR) Тип постоянного обратного итератора для управляемой последовательности.
vector::difference_type (STL/CLR) Тип расстояния со знаком между двумя элементами.
vector::generic_container (STL/CLR) Тип универсального интерфейса для контейнера.
vector::generic_iterator (STL/CLR) Тип итератора для универсального интерфейса для контейнера.
vector::generic_reverse_iterator (STL/CLR) Тип реверсивного итератора для универсального интерфейса контейнера.
vector::generic_value (STL/CLR) Тип элемента для универсального интерфейса контейнера.
vector::iterator (STL/CLR) Тип итератора для управляемой последовательности.
vector::reference (STL/CLR) Тип ссылки на элемент.
vector::reverse_iterator (STL/CLR) Тип обратного итератора для управляемой последовательности.
vector::size_type (STL/CLR) Тип расстояния со знаком между двумя элементами.
vector::value_type (STL/CLR) Тип элемента.
Функция-член Описание
vector::assign (STL/CLR) Заменяет все элементы.
vector::at (STL/CLR) Обращается к элементу в указанной позиции.
vector::back (STL/CLR) Обращается к последнему элементу.
vector::begin (STL/CLR) Задает начало управляемой последовательности.
vector::capacity (STL/CLR) Возвращает объем пространства, выделенного для хранения контейнера.
vector::clear (STL/CLR) Удаляет все элементы.
vector::empty (STL/CLR) Проверяет отсутствие элементов.
vector::end (STL/CLR) Задает конец управляемой последовательности.
vector::erase (STL/CLR) Удаляет элементы в указанных позициях.
vector::front (STL/CLR) Обращается к первому элементу.
vector::insert (STL/CLR) Добавляет элементы в указанную позиции.
vector::pop_back (STL/CLR) Удаляет последний элемент.
vector::push_back (STL/CLR) Добавляет новый последний элемент.
vector::rbegin (STL/CLR) Задает начало обратной управляемой последовательности.
vector::rend (STL/CLR) Задает конец обратной управляемой последовательности.
vector::reserve (STL/CLR) Обеспечивает минимальный объем роста для контейнера.
vector::resize (STL/CLR) Изменяет количество элементов.
vector::size (STL/CLR) Подсчитывает количество элементов.
vector::swap (STL/CLR) Меняет местами содержимое двух контейнеров.
vector::to_array (STL/CLR) Копирует управляемую последовательность в новый массив.
vector::vector (STL/CLR) Создает объект контейнера.
Свойство Описание
vector::back_item (STL/CLR) Обращается к последнему элементу.
vector::front_item (STL/CLR) Обращается к первому элементу.
Оператор Описание
vector::operator= (STL/CLR) Заменяет управляемую последовательность.
vector::operator (STL/CLR) Обращается к элементу в указанной позиции.
operator! = (вектор) (STL/CLR) Определяет vector , не равен ли объект другому vector объекту.
Оператор< (Vector) (STL/CLR) Определяет vector , меньше ли объект, чем другой vector объект.
Оператор<= (Vector) (STL/CLR) Определяет, vector является ли объект меньшим или равным другому vector объекту.
оператор = = (Vector) (STL/CLR) Определяет vector , равен ли объект другому vector объекту.
operator> (vector) (STL/CLR) Определяет vector , больше ли объект, чем другой vector объект.
Оператор>= (Vector) (STL/CLR) Определяет vector , больше или равен ли объект другому vector объекту.

Читайте также: