Table of contents
1.
Introduction
2.
Find the Size of the Vector in C++
2.1.
C++
3.
C++ Program to Find the Size of the Vector
3.1.
C++
3.2.
In this program
4.
Time & Space Complexity
4.1.
Time Complexity
4.2.
Space Complexity
5.
Frequently Asked Questions
5.1.
What happens if I try to access an element out of the vector's range using the at() function?
5.2.
How can I reduce the memory overhead of a vector if I know it won't grow further?
5.3.
Is it efficient to frequently add and remove elements from the beginning of a vector?
6.
Conclusion
Last Updated: Oct 1, 2024
Medium

Vector Size in C++

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C++, vectors are a powerful & versatile data structure that allows you to store & manage collections of elements. One important aspect of working with vectors is determining their size, which refers to the number of elements currently stored in the vector. Knowing the size of a vector is crucial for various operations & algorithms. 

Vector Size in C++

In this article, we will learn about different ways to find the size of a vector in C++, along with code examples & explanations with their respective time & space complexity.

Find the Size of the Vector in C++

In C++, vectors are used because they are more flexible than traditional arrays. One of the most common tasks when working with vectors is determining their size. The size of a vector tells you how many elements it currently holds, which is crucial for running loops, making decisions, and managing resources effectively.

To find the size of a vector, C++ provides a simple method called size(). This method returns the number of elements in the vector. Here's how you can use it:

  • C++

C++

#include <iostream>
#include <vector>

int main() {
// Create a vector containing integers
std::vector<int> vec = {10, 20, 30, 40, 50};

// Print the size of the vector
std::cout << "The size of the vector is: " << vec.size() << std::endl;

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

The size of the vector is: 5


In this example, the vector vec is initialized with five integers. The size() method is then called to print the size of the vector, which in this case would output 5 because there are five elements stored in the vector.

Note -: Learning this method is very useful because it helps you manage how your program handles data stored in vectors, ensuring that you do not exceed the vector's limit or waste memory.

C++ Program to Find the Size of the Vector

Now look at a proper C++ program to understand this properly.  This program will not only retrieve the size of a vector but also show how the size changes as we add and remove elements. This is crucial for applications where dynamic data structures are used to handle varying amounts of data.

  • C++

C++

#include <iostream>

#include <vector>

int main() {

   // Creating a vector to store integers

   std::vector<int> vec;

   // Adding elements to the vector

   vec.push_back(5);

   vec.push_back(10);

   vec.push_back(15);

   // Printing the size after adding elements

   std::cout << "Initial size of the vector: " << vec.size() << std::endl;

   // Removing an element from the vector

   vec.pop_back();

   // Printing the size after removing an element

   std::cout << "Size of the vector after one element is removed: " << vec.size() << std::endl;

   return 0;

}
You can also try this code with Online C++ Compiler
Run Code

Output

Initial size of the vector: 3
Size of the vector after one element is removed: 2

In this program

  1. We start with an empty vector of integers.
     
  2. We add three integers to the vector using push_back(), which increases the size of the vector each time an element is added.
     
  3. After adding the elements, we check the size of the vector using vec.size(), which should now return 3.
     
  4. We then remove the last element from the vector using pop_back(), which decreases the size of the vector.
     
  5. After removing the element, we check the size again, which should now be 2.
     

Note -: This example is essential for understanding how vector sizes adjust dynamically, which helps in writing programs that need to adjust to the changing data sizes efficiently.

Time & Space Complexity

When working with vectors in C++, it's important to consider the time and space complexity of operations like adding, removing, and accessing elements. This understanding helps in writing efficient code, especially when dealing with large amounts of data.

Time Complexity

  1. Accessing an Element: Accessing an element by its index in a vector is a constant time operation, O(1). This means it takes the same amount of time regardless of the size of the vector.
     
  2. Adding an Element: Adding an element to the end of the vector (using push_back()) also has a time complexity of O(1), generally. However, if the addition of an element exceeds the current capacity of the vector, the vector needs to increase its capacity, which involves allocating a new array and copying all elements to this new space. This operation has a time complexity of O(n), where n is the number of elements in the vector. But such cases are amortized and rare.
     
  3. Removing an Element: Removing the last element of a vector using pop_back() is a constant time operation, O(1). However, removing elements from other positions can be more costly as it requires shifting the elements.

Space Complexity

  • The space complexity of a vector is O(n), where n is the number of elements it contains. Vectors manage their storage automatically and can grow dynamically. Although this provides flexibility, it requires careful management to avoid excessive memory use, especially in programs dealing with a large amount of data.

Frequently Asked Questions

What happens if I try to access an element out of the vector's range using the at() function?

If you attempt to access an element outside the vector's range using the at() function, it will throw an out_of_range exception. This is safer compared to using square brackets [], which do not perform any bounds checking.

How can I reduce the memory overhead of a vector if I know it won't grow further?

To reduce the memory overhead of a vector after it has reached its required size, you can use the shrink_to_fit() method. This advises the vector to reduce its capacity to fit its size, potentially freeing up memory.

Is it efficient to frequently add and remove elements from the beginning of a vector?

Adding or removing elements from the beginning of a vector is generally inefficient because each operation requires shifting all the subsequent elements. For operations that involve frequent insertions and deletions at the beginning, consider using std::deque or std::list which are more suited for these tasks.

Conclusion

In this article, we have learned how to find and manage the size of a vector in C++. We explored practical examples of adding and removing elements, discussed their time and space complexity, and answered some common questions that arise when dealing with vectors. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass