0
0
CppConceptBeginner · 3 min read

What is vector in C++: Explanation and Example

In C++, a vector is a dynamic array that can grow or shrink in size automatically. It stores elements in contiguous memory and provides fast access and easy management of collections of data.
⚙️

How It Works

A vector in C++ works like a flexible list that can change its size as you add or remove items. Imagine a row of boxes where you can put your toys. If you get more toys, the row automatically grows to fit them, and if you give some away, it shrinks.

Under the hood, a vector uses a block of memory to store elements one after another. When it runs out of space, it creates a bigger block, copies the old items there, and frees the old block. This makes it easy to access any item quickly by its position, just like looking at a specific box in the row.

💻

Example

This example shows how to create a vector, add numbers to it, and print them out.

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers;  // Create an empty vector of integers
    numbers.push_back(10);     // Add 10
    numbers.push_back(20);     // Add 20
    numbers.push_back(30);     // Add 30

    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
Output
10 20 30
🎯

When to Use

Use a vector when you need a list of items that can change size during your program. It is perfect for storing things like scores, names, or any collection where you don't know the exact number of elements ahead of time.

For example, if you are making a game and want to keep track of all the players joining or leaving, a vector lets you add or remove players easily without worrying about the size limits.

Key Points

  • Dynamic size: grows or shrinks automatically.
  • Contiguous memory: stores elements next to each other for fast access.
  • Easy to use: provides simple functions like push_back to add items.
  • Safe and efficient: manages memory automatically.

Key Takeaways

A vector is a dynamic array that automatically adjusts its size.
It stores elements in contiguous memory for fast access by index.
Use vectors when you need a flexible list that can grow or shrink.
Vectors provide easy-to-use functions like push_back to add elements.
They manage memory safely and efficiently without manual handling.