×

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
  1. 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.
  2. 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.
  3. 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:

Vector Size in C++

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:

Vector Size in C++

Related Topics

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible. The memory size for static arrays determines at compile...

4 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

OOPs Concepts in C++

C++ Object-Oriented Programming Concepts C++ uses the concept of object-oriented programming. Object Oriented Programming has some prominent features: Object Class Data abstraction Encapsulation Polymorphism Inheritance Message passing Object An object is the basic unit...

2 minutes read.

C++ Call by Value

In this article, we will discuss C++ Call by Value with their syntax, examples, use cases, advantages, and disadvantages. C++ Function A function is a set of statements that executes a task....

5 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

C++ Pipe Tutorial

A pipe is a mechanism for inter-process communication (IPC) in a Unix-like operating system. It allows two or more processes to communicate with each other by sending and receiving data...

3 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

How is multiset implemented in C++

Similar to sets, multisets are an associative container type where several items may share the same values. Associative containers implement instantly searchable sorted data structures with O(log n) complexity. In a multiset,...

5 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Dynamic Memory Allocation in C++

In some programming situations, the number of data items changes as the program is running, which is known as dynamic data or input. Consider a real-world situation where a program...

3 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

C++ Heap Sort

Heapsort is executed on the structure of the heap data. We know heap is a complete tree in binary form. The heap tree can be of two different types: Min-heap,...

3 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.