×

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

C++ vs C#

What exactly is C++ programming? Bjorne Stroustrup is the creator of the C++ programming language. His goal was to create a powerful object-oriented programming language with the capabilities of C. It...

4 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Multilevel Inheritance

C++ Multilevel Inheritance Multilevel inheritance is such an inheritance in which a derived class is created from another derived class. C++ Multilevel Inheritance Example In this example, a base class Student is inherited in...

2 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Program that produces different results in C and C++

Introduction: There are many such programs that compile run both in C and C++ but give different outcomes when compiled by the C and C++ compilers. There are a variety of such...

6 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

2 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

abs() function in C++

In C++, the abs() function returns the absolute value of any integer number. Using this function a negative integer is multiplied by -1 and positive number or zero is returned...

4 minutes read.