Vector Size in C++


We can get the size of a vector using the .size() method:

vector<int> ourArray = {50, 40, 30};

// Printing the size:
cout << ourArray.size() << endl; // Output: 3

// Changing the vector:
ourArray.pop_back();

// Printing the new size:
cout << ourArray.size() << endl; // Output: 2

Using the size

We can use the size to access items from the end of a vector.

Because vectors are 0-indexed, the index of the last item is size - 1:

vector<int> ourArray = {50, 40, 30};

int size = ourArray.size();

// Printing the last item:
cout << ourArray[size - 1] << endl; // Output: 30

// Printing the second to last item:
cout << ourArray[size - 2] << endl; // Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


Introduction

In this lesson, we will explore how to determine the size of a vector in C++ using the .size() method. Vectors are dynamic arrays that can change in size, making them a versatile tool in programming. Understanding how to work with vector sizes is crucial for efficient data manipulation and management.

Understanding the Basics

Vectors in C++ are part of the Standard Template Library (STL) and provide a way to store dynamic arrays. The .size() method returns the number of elements currently stored in the vector. This is important for iterating over the vector, accessing elements, and performing operations that depend on the vector's length.

Here is a simple example to illustrate the concept:

vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Size of vector: " << numbers.size() << endl; // Output: 5

Main Concepts

The key concept here is the .size() method, which provides the current number of elements in the vector. This method is essential for various operations, such as iterating through the vector or accessing elements from the end.

Let's see how to use the size to access the last element of a vector:

vector<int> numbers = {10, 20, 30, 40, 50};
int lastIndex = numbers.size() - 1;
cout << "Last element: " << numbers[lastIndex] << endl; // Output: 50

Examples and Use Cases

Here are some examples demonstrating the use of the .size() method in different contexts:

vector<string> fruits = {"apple", "banana", "cherry"};
cout << "Number of fruits: " << fruits.size() << endl; // Output: 3

// Removing the last fruit
fruits.pop_back();
cout << "Number of fruits after pop_back: " << fruits.size() << endl; // Output: 2

// Accessing the last fruit
cout << "Last fruit: " << fruits[fruits.size() - 1] << endl; // Output: banana

Common Pitfalls and Best Practices

One common mistake is trying to access an element using an index that is out of bounds, especially after modifying the vector. Always ensure that the index is within the valid range (0 to size-1).

Best practices include checking the size before accessing elements and using iterators for safe traversal:

vector<int> numbers = {1, 2, 3};
if (!numbers.empty()) {
    cout << "First element: " << numbers.front() << endl;
}

Advanced Techniques

Advanced techniques involve using the size in combination with other vector methods for more complex operations. For example, resizing a vector or using the size to control loops:

vector<int> numbers = {1, 2, 3, 4, 5};
numbers.resize(3); // Resize vector to contain only 3 elements
cout << "Resized vector size: " << numbers.size() << endl; // Output: 3

Code Implementation

Here is a complete example demonstrating the use of the .size() method:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> ourArray = {50, 40, 30};

    // Printing the size
    cout << "Initial size: " << ourArray.size() << endl; // Output: 3

    // Changing the vector
    ourArray.pop_back();

    // Printing the new size
    cout << "Size after pop_back: " << ourArray.size() << endl; // Output: 2

    // Accessing elements using size
    int size = ourArray.size();
    cout << "Last element: " << ourArray[size - 1] << endl; // Output: 40

    return 0;
}

Debugging and Testing

When debugging, ensure that you are not accessing elements out of the vector's bounds. Use assertions or checks to validate the size before accessing elements:

#include <cassert>

vector<int> numbers = {1, 2, 3};
assert(numbers.size() == 3);

For testing, write test cases that cover different scenarios, such as empty vectors, vectors with one element, and vectors after modifications.

Thinking and Problem-Solving Tips

When working with vectors, always consider edge cases like empty vectors or vectors with a single element. Break down the problem into smaller parts and handle each part carefully. Practice by solving problems that involve dynamic arrays and vector manipulations.

Conclusion

Understanding how to work with vector sizes in C++ is fundamental for efficient programming. The .size() method is a powerful tool that helps manage and manipulate dynamic arrays effectively. By mastering these concepts, you can write more robust and efficient code.

Additional Resources