Как узнать длину вектора c
Для добавления элементов в вектор применяется функция push_back() , в которую передается добавляемый элемент:
Векторы являются динамическими структурами в отличие от массивов, где мы скованы его заданым размером. Поэтому мы можем динамически добавлять в вектор новые данные.
Функция emplace_back() выполняет аналогичную задачу — добавляет элемент в конец контейнера:
Добавление элементов на определенную позицию
Ряд функций позволяет добавлять элементы на определенную позицию.
emplace(pos, value) : вставляет элемент value на позицию, на которую указывает итератор pos
insert(pos, value) : вставляет элемент value на позицию, на которую указывает итератор pos, аналогично функции emplace
insert(pos, n, value) : вставляет n элементов value начиная с позиции, на которую указывает итератор pos
insert(pos, begin, end) : вставляет начиная с позиции, на которую указывает итератор pos, элементы из другого контейнера из диапазона между итераторами begin и end
insert(pos, values) : вставляет список значений начиная с позиции, на которую указывает итератор pos
Удаление элементов
Если необходимо удалить все элементы вектора, то можно использовать функцию clear :
Функция pop_back() удаляет последний элемент вектора:
Если нужно удалить элемент из середины или начала контейнера, применяется функция std::erase() , которая имеет следующие формы:
erase(p) : удаляет элемент, на который указывает итератор p. Возвращает итератор на элемент, следующий после удаленного, или на конец контейнера, если удален последний элемент
erase(begin, end) : удаляет элементы из диапазона, на начало и конец которого указывают итераторы begin и end. Возвращает итератор на элемент, следующий после последнего удаленного, или на конец контейнера, если удален последний элемент
Также начиная со стандарта С++20 в язык была добавлена функция std::erase() . Она не является частью типа vector. В качестве первого параметра она принимает вектор, а в качестве второго — элемент, который надо удалить:
В данном случае удаляем из вектора numbers3 все вхождения числа 1.
Размер вектора
С помощью функции size() можно узнать размер вектора, а с помощью функции empty() проверить, путой ли вектор:
С помощью функции resize() можно изменить размер вектора. Эта функция имеет две формы:
resize(n) : оставляет в векторе n первых элементов. Если вектор содержит больше элементов, то его размер усекается до n элементов. Если размер вектора меньше n, то добавляются недостающие элементы и инициализируются значением по умолчанию
resize(n, value) : также оставляет в векторе n первых элементов. Если размер вектора меньше n, то добавляются недостающие элементы со значением value
Важно учитывать, что применение функции resize может сделать некорректными все итераторы, указатели и ссылки на элементы.
Изменение элементов вектора
Функция assign() позволяет заменить все элементы вектора определенным набором:
В данном случае элементы вектора заменяются набором из четырех строк «C++».
Также можно передать непосредственно набор значений, который заменит значения вектора:
Еще одна функция — swap() обменивает значения двух контейнеров:
Сравнение векторов
Векторы можно сравнивать — они поддерживают все операции сравнения: <, >, <=, >=, ==, !=. Сравнение контейнеров осуществляется на основании сравнения пар элементов на тех же позициях. Векторы равны, если они содержат одинаковые элементы на тех же позициях. Иначе они не равны:
C++ vector size

In C++, Vectors are called dynamic arrays that can automatically resize themselves when an item is inserted or removed, with its storage being controlled automatically by the container. Vector items are kept in adjacent storage, which is easy to access and traverse with the help of iterators. Moreover, items are inserted at the end, and it may take some time as an extension of the array is needed in certain cases. There are several functions that support vector operations, and size() is one such function that helps in returning the vector size of the container or count of items available in it. In this topic, we are going to learn about the C++ vector size.
Web development, programming languages, Software testing & others
Syntax
While learning a new concept in a programming language, you have to understand the same basic syntax. So, let us see the syntax of the size() function in vector.
Here, vec is the name of the vector
Parameters of the function:
Unlike other functions, no parameters are passed in this.
Return value:
Count of items in the container.
Exceptions and Errors
- Do not guarantee exception throw.
- When parameters are passed, errors are thrown.
How to find the size of vector in C++?
As I have already mentioned, size() is one of the vector functions that help in returning the vector size of the container or count of items available in it.
For example, consider a vector vtr as mentioned below.
From this, we can see that there are 5 elements in the vector. So, when we call the size() function, the result will display the size of the vector as 5.
It can be used while performing addition operations in the vector. Instead of mentioning the size, the size() function can be used.
Examples of C++ vector size
Now, let us see some sample programs on the size function of vector in C++ for a better understanding.
Example #1
CPP program that demonstrates the implementation of size() function in vector
Code:
Output:
![]()
First, this program imports all the necessary header files such as <iostream> and <vector>. After this, a vector is declared with few elements. On executing the code, the size of the vector is printed using the size() function.
Example #2
CPP program that uses size() function in vector for adding all the vector elements.
Code:
Output:

In this program, a vector is declared with few elements and also, a variable s is declared for storing the sum of the elements. On executing the code, the size of the vector is printed using the size() function, and the sum of the elements is printed using a for a loop.
Example #3
CPP program that uses size() function for a string vector
Code:
Output:
![]()
In this program, a vector is declared with string elements, unlike the above programs. But, the size() function prints the size of the vector.
Example #4
CPP program that creates an empty vector and prints the size
Code:
Output:
![]()
In this program, a vector is declared with no elements, and on executing the code, the size of the vector will be displayed as 0.
Example #5
CPP program that declares a vector add elements and print size
Code:
Output:
![]()
An empty vector is declared in this program, and elements are added to it using a for a loop. Then, the size of the vector is printed using the size() function.
Example #6
CPP program that inserts elements to vector end and print size
Code:
Output:
![]()
In this program also, an empty vector is declared first, and elements are added to the end of the vector using insert(). Then, the size of the vector is printed using the size() function.
Conclusion
size() is a method that helps in returning the vector size of the container or count of items available in a vector. In this article, different aspects such as syntax, working, and examples of size() function are explained in detail.
Recommended Articles
This is a guide to the C++ vector size. Here we discuss How to find the size of vector work in C++ and Examples along with the codes and outputs. You can also look at the following article to learn more –
How can I get the size of an std::vector as an int?
![]()
In the first two cases, you simply forgot to actually call the member function (!, it’s not a value) std::vector<int>::size like this:
Your third call
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.
Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.
C++ Vector Size or Length
In this C++ tutorial, you will learn how to get the size or length of a vector using vector::size() function, with examples.
C++ Vector Size
To get the size of a C++ Vector, you can use size() function on the vector.
size() function returns the number of elements in the vector.
Examples
1. Find Vector Length using size()
In the following C++ program, we define a vector of integers, add some elements to it, and then find its length using size() function.
C++ Program
Output
2. Length of Empty Vector
In the following C++ program, we define a vector of integers, with no elements in it, and then find its length using size() function. size() should return a value of zero.
C++ Program
Output
3. Length of Vector using Foreach
You can also use C++ Foreach statement to get the length of size of a vector.
In the following program, we shall define a vector and initialize with elements. Then take a len variable with zero initial value that acts as a counter to count the number of elements in the vector. Use Foreach statement to iterate over the elements of vector and increment the counter during each iteration.
C++ Program
Output
Conclusion
In this C++ Tutorial, we learned to find the size of vector, which is the number of elements in a vector using builtin functions or statements like foreach.