Vector Size in C++
What are Vectors?
In the C++ programming language, vectors are run-time sequence containers representing arrays with variable sizes, which are contained within STL (Standard Template Library). They utilize contiguous storage spaces for their elements just as effectively as arrays do. Therefore, their elements can also be accessed using offsets on standard pointers to their elements.
As opposed to arrays, which are static in nature and only store sequential data, vectors give the application more flexibility and are dynamic in nature. When an element is added to or removed from a vector, the vector's size gets automatically change.
In C++, vectors do not have an ordering. Iterators can quickly access and traverse vector elements that are stored in nearby storage.
When using the push back() function in vectors, data is added at the end. It takes more time to insert an element at the end of a vector because the vector may need to be extended occasionally. Still, it only takes time to insert an element at the beginning or the middle. Since no scaling occurs, removing the final element just requires constant time.
Introduction to Vector Size
When an item is added or withdrawn, a dynamic array, also known as a vector, can automatically resize itself.
The container controls how much space the vector has to store the item. With the use of iterators, nearby storage that is where the vector elements are held is simple to access and navigate.
Additionally, because items are added in the end, it could take a while because there are times when an array extension is required.
There are numerous functions that assist with vector operations, and one of them is the size(), which aids in determining the container's vector size or the number of items it contains.
Syntax:
Let's now look at the size() function's syntax in a vector.
Vec_name.size()
The vector's name, in this case, is Vec_name.size().
- Function parameters: This function doesn't accept any parameters, unlike other functions.
- Return value: The number of objects in the container.
- Exceptions and Errors: Do not ensure that an exception will be thrown. Errors are thrown whenever parameters are passed.
Member Functions of a C++ Vector:
Three types of C++ vector member functions can be distinguished:
- Modifiers
- Iterators
- Capacity
- Modifiers: These are functions that are used to alter or modify the vector, as the name implies. For instance, assign() can be used to remove the vector's current value and replace it with a new one.
- Iterators: Iterator functions are used to traverse or loop through the vector's elements. For instance, the vector's final element can be pointed to using the end() function.
- Capacity: The operations that fall under this category have to deal with size, such as altering the size of a vector. For instance, the size of the vector can be changed using the resize(n) function.
Initializing a Vector
Instead of storing the data directly, the vector in C++ stores the references to the objects. These objects can have any data type, such as an integer, a character, a string, etc. A vector does not need to be initialized with a size, in contrast to static containers like an array. Since the container's size might change dynamically, we don't need to specify it when we initialize a vector.
How to calculate a Vector's size in C++?
Size() is one of the vector functions that can be used to return the container's vector size or the number of items that are present in it, as I've already mentioned.
Take a vector vpn, as it is described below, as an example.
vector[int] [vpn][31, 52, 63, 84, 57];
This allows us to determine that the vector contains 5 entries. Consequently, the size() function's output will indicate that the vector's size is 5, and we can see this by calling it.
When working with the vector's addition operations, it can be utilized. The size() function can be used in place of providing the size information.
Examples of vector sizes in C++
Now, for a better understanding, let's look at some examples of C++ programs that implement the size function of vectors.
Program:1
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//declare a vector
vector<int> vpn{ 8, 5, 6, 7, 9, 3, 2 };
//print the size of a vector
cout <<"The vector size is: " << vpn.size()<<endl;
return 0;
}
Explanation:
- In above code, the #include directive instructs the preprocessor to include the contents of the iostream file in the program. It includes declarations for the identifier cout, cin, insertion operator (<<), and extraction operator (>>).
- We included #include <vector>, to instruct the compiler to compile the vector file in addition to our code. Without including the file, the compiler won't be aware of the existence of the class std::vector, so we cannot use it. The standard library of C++ is unknown to the compiler.
- The scope of the identifiers used in a program is defined by the namespace. We must include the using directive in order to use the identifiers defined in the namespace scope.
- In the main() function, we have declared a variable "i," which has an "int" data type. In this variable, we will store the result of the sum.
- Next, we declared the vector "vpn," which has the data type "int," initialized it as an array, and assigned the values 45, 60, 70, 85, and 87.
- Then, we use cout; cout is the object of an ostream class. The Iostream header file contains its definition. It serves as a means of displaying the output on the monitor, which is the usual output device.
- Inserting a new line character, we use here endl Command.
- As code executes, a message indicating the vector's size will appear on the screen. To determine the vector's size, we utilize the size() method.
Program Output:
Program: 2
#include <iostream>
#include <vector>
using namespace std;
//main method
int main()
{
//declare a variable to store the sum
int a = 0;
//declare a vector
vector<int> vpn{ 45, 60, 70, 85, 87 };
//print the size of a vector
cout <<"The vector size is: " << vpn.size();
// using the loop, obtain the element's sum.
while (vpn.size() > 0) {
a = a + vpn.back();
vpn.pop_back();
}
cout <<endl<<" Sum of the vector elements is: " << a;
return 0;
}
Explanation:
- In the above code, we have declared a variable "i," which has an "int" data type. In this variable, we will store the result of the sum.
- Next, we declared the vector "vpn," which has the data type "int," initialized it as an array, and assigned the values 45, 60, 70, 85, and 87.
- Then, we use cout; cout is the object of an ostream class. The Iostream header file contains its definition. It serves as a means of displaying the output on the monitor, which is the usual output device.
- Inserting a new line character, we use here endl Command.
- After the code has run, a message indicating the vector's size will appear on the screen. To determine the vector's size, we utilize the size() method.
- Next, we employed the while loop, which enables us to obtain the sum of the elements.
- In this loop, we have a condition that the size of the vector (vpn.back()) must be greater than to zero, when this condition is satisfied, we will enter the body of the loop.
- In the body, we performed an arithmetic operation in which we added the “a” variable and the function vpn.back()to store the result in variable “a”.
- Then we used pop.back() function, with the help of this function, the list container's size is decreased by 1, and the last element is removed or pops, making its predecessor the last element.
- Then we will get the result of the sum on the display with the help of the cout object.
Program Output: