C++ Vectors

C++ Vectors: Dynamic Arrays

In standard C++, an array has a fixed size. Once you declare an array of size 5, it cannot hold a 6th element. This limitation is solved by Vectors.

A vector in C++ is a dynamic array provided by the STL. It can automatically resize itself whenever elements are added or removed.


1. Using Vectors

To use a vector, you must include the <vector> library at the top of your program.

Syntax:

#include <vector>

// vector<DataType> vectorName; vector<int> numbers;


2. Adding and Removing Elements

Vectors are incredibly flexible. You can easily add elements to the end of a vector using .push_back(), and remove the last element using .pop_back().

Vector Operations Example

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

int main() { // Create an empty vector of strings vector<string> cars;

// Add elements cars.push_back("Volvo"); cars.push_back("BMW"); cars.push_back("Ford");

// Access the first element cout << "First car: " << cars.front() << "\n";

// Remove the last element ("Ford") cars.pop_back();

// Check the current size cout << "Total cars now: " << cars.size() << "\n";

return 0; }


3. Why Use Vectors over Standard Arrays?

  1. Dynamic Size: You don't need to know the size of the array at compile time.
  2. Built-in Functions: Vectors come with incredibly useful methods like .size(), .empty(), .clear(), and more.
  3. Memory Management: The vector handles its own memory dynamically behind the scenes, preventing many memory-leak issues that plague manual C++ arrays.

Exercise

?

Which function is used to add an element to the end of a vector?