Vector assign c описание

Обновлено: 04.07.2024

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.

Векторы аналогичны динамическим массивам с возможностью автоматического изменения размера при вставке или удалении элемента, при этом их хранение автоматически обрабатывается контейнером.

вектор :: в ()

Функция at () используется для ссылки на элемент, присутствующий в позиции, заданной в качестве параметра функции.
Синтаксис:

Ошибки и исключения

1. Если позиция не присутствует в векторе, она выбрасывает out_of_range .
2. В противном случае он имеет сильную гарантию броска без исключения.

using namespace std;

vector< int > myvector;

заявка
Учитывая вектор целых чисел, выведите все целые числа, присутствующие в четных позициях.

Алгоритм
1. Запустите цикл до размера вектора.
2. Проверьте, делится ли позиция на 2, если да, напечатайте элемент в этой позиции.

using namespace std;

vector< int > myvector;

// вектор становится 1, 2, 3, 4, 5, 6, 7, 8, 9

for ( int i = 0; i < myvector.size(); i += 2)

вектор :: своп ()

Эта функция используется для замены содержимого одного вектора на другой вектор того же типа и размера.

Синтаксис:

Ошибки и исключения

1. Выдает ошибку, если вектор не одного типа.
2. Выдает ошибку, если вектор не одного размера.
2. В противном случае он имеет основную гарантию броска без исключения.

Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly.

In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order.

In the fill version (2), the new contents are n elements, each initialized to a copy of val.

If a reallocation happens,the storage needed is allocated using the internal allocator.

In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order.

In the fill version (2), the new contents are n elements, each initialized to a copy of val.

In the initializer list version (3), the new contents are copies of the values passed as initializer list, in the same order.

The internal allocator is used (through its traits) to allocate and deallocate storage if a reallocation happens. It is also used to destroy all existing elements, and to construct the new ones.

Any elements held in the container before the call are destroyed and replaced by newly constructed elements (no assignments of elements take place).

This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

Assigns new contents to the vector, replacing its current contents, and modifying its size accordingly.

In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order.

In the fill version (2), the new contents are n elements, each initialized to a copy of val.

If a reallocation happens,the storage needed is allocated using the internal allocator.

In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order.

In the fill version (2), the new contents are n elements, each initialized to a copy of val.

In the initializer list version (3), the new contents are copies of the values passed as initializer list, in the same order.

The internal allocator is used (through its traits) to allocate and deallocate storage if a reallocation happens. It is also used to destroy all existing elements, and to construct the new ones.

Any elements held in the container before the call are destroyed and replaced by newly constructed elements (no assignments of elements take place).

This causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.

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