Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Understanding Vectors in C++

Introduction

A vector in C++ is a dynamic array that can grow or shrink in size. It is part of the Standard Template Library (STL) and provides a safer and more flexible alternative to traditional arrays. Vectors are defined in the <vector> header and reside within the std namespace.

Creating a Vector

To create a vector, you need to include the <vector> header and use the std::vector template:

#include <vector>
#include <iostream>
int main() {
  std::vector<int> numbers;
  return 0;
}

Adding Elements to a Vector

You can add elements to a vector using the push_back method:

numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);

This will add the elements 10, 20, and 30 to the vector.

Accessing Elements

Elements in a vector can be accessed using the [] operator or the at method:

int first = numbers[0];
int second = numbers.at(1);

The above code will access the first and second elements of the vector.

Iterating Over a Vector

You can iterate over a vector using a loop:

for (size_t i = 0; i < numbers.size(); ++i) {
  std::cout << numbers[i] << " ";
}

This will print all the elements in the vector.

Removing Elements

To remove elements from a vector, you can use the pop_back method or the erase method:

numbers.pop_back();
// Removes the last element
numbers.erase(numbers.begin() + 1);
// Removes the second element

Vector Capacity

Vectors have several methods to manage their capacity:

numbers.size(); // Returns the number of elements
numbers.capacity(); // Returns the size of storage space currently allocated
numbers.reserve(10); // Requests that the vector capacity be at least enough to contain 10 elements

Clearing a Vector

To remove all elements from a vector, use the clear method:

numbers.clear();

This will remove all elements from the vector, reducing its size to 0.

Conclusion

Vectors are a powerful and flexible way to manage dynamic arrays in C++. They provide numerous methods for adding, accessing, and managing elements, making them an essential tool in any C++ programmer's toolkit. With this tutorial, you should now have a solid understanding of how vectors work and how to use them effectively.