Vector Basics

Basic Vector Operations in C++

BeginnerTopic: STL Containers Programs
Back

C++ Vector Basics Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
#include <vector>
using namespace std;

int main() {
    // Create vector
    vector<int> vec;
    
    // Add elements
    vec.push_back(10);
    vec.push_back(20);
    vec.push_back(30);
    vec.push_back(40);
    vec.push_back(50);
    
    cout << "Vector elements: ";
    for (int i = 0; i < vec.size(); i++) {
        cout << vec[i] << " ";
    }
    cout << endl;
    
    // Access elements
    cout << "First element: " << vec.front() << endl;
    cout << "Last element: " << vec.back() << endl;
    cout << "Element at index 2: " << vec.at(2) << endl;
    
    // Size and capacity
    cout << "Size: " << vec.size() << endl;
    cout << "Capacity: " << vec.capacity() << endl;
    
    // Initialize vector with values
    vector<int> vec2 = {1, 2, 3, 4, 5};
    cout << "\nVector 2: ";
    for (int num : vec2) {
        cout << num << " ";
    }
    cout << endl;
    
    // Remove last element
    vec.pop_back();
    cout << "\nAfter pop_back: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
    
    return 0;
}
Output
Vector elements: 10 20 30 40 50
First element: 10
Last element: 50
Element at index 2: 30
Size: 5
Capacity: 8

Vector 2: 1 2 3 4 5

After pop_back: 10 20 30 40

Understanding Vector Basics

This program teaches you how to use Vector Basics in C++. Vector is a dynamic array from the STL (Standard Template Library) that can resize automatically. It provides random access, efficient insertion/deletion at the end, and automatically manages memory allocation.

---

1. What This Program Does

The program demonstrates basic vector operations:

Creating and initializing vectors
Adding elements with push_back()
Accessing elements (front, back, at, index)
Getting size and capacity
Removing elements with pop_back()

Vectors are the most commonly used STL container.

---

2. Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <vector>
Provides vector container class.

---

3. Understanding Vectors

Vector Concept

:

Dynamic array that resizes automatically
Elements stored contiguously in memory
Random access (like arrays)
Efficient insertion/deletion at end

Key Features

:

Automatic memory management
Can grow and shrink dynamically
Cache-friendly (contiguous memory)
Part of STL (Standard Template Library)

---

4. Creating Vectors

Empty Vector

:

vector<int> vec;

Initialized Vector

:

vector<int> vec2 = {1, 2, 3, 4, 5};

How it works

:

Template syntax: vector<dataType>
Can hold any data type
Initially empty (size 0)
Can initialize with values

---

5. Adding Elements

push_back()

:

vec.push_back(10);

vec.push_back(20);

vec.push_back(30);

How it works

:

Adds element to end of vector
Automatically resizes if needed
O(1) amortized time complexity
Most efficient way to add elements

---

6. Accessing Elements

Methods

:

vec[i]: array-like access (no bounds check)
vec.at(i): access with bounds check (throws exception)
vec.front(): first element
vec.back(): last element

Example

:

vec.front() // Returns 10

vec.back() // Returns 30

vec.at(2) // Returns 30 (with bounds check)

vec[1] // Returns 20 (no bounds check)

---

7. Size and Capacity

Size

:

vec.size() // Number of elements

Capacity

:

vec.capacity() // Allocated memory size

How it works

:

Size: actual number of elements
Capacity: memory allocated (usually larger)
Vector pre-allocates extra memory
Resizes when capacity exceeded

---

8. Removing Elements

pop_back()

:

vec.pop_back(); // Removes last element

How it works

:

Removes element from end
O(1) time complexity
Reduces size (not capacity)
Efficient operation

---

9. When to Use Vectors

Best For

:

Dynamic arrays (size changes)
Random access requirements
Frequent insertion/deletion at end
General-purpose container
Most common STL container

Example Scenarios

:

Reading unknown number of elements
Dynamic data structures
Arrays that need to grow
General data storage

---

10. Important Considerations

Memory Layout

:

Elements stored contiguously
Cache-friendly (good performance)
Like arrays but dynamic

Performance

:

push_back(): O(1) amortized
pop_back(): O(1)
Random access: O(1)
Insert/delete in middle: O(n)

Automatic Management

:

Memory allocated automatically
Resizes when needed
No manual memory management
Exception-safe

---

11. return 0;

This ends the program successfully.

---

Summary

Vector: dynamic array that resizes automatically, part of STL.
push_back(): adds element to end, automatically resizes.
Access: vec[i], vec.at(i), vec.front(), vec.back().
size(): number of elements, capacity(): allocated memory.
pop_back(): removes last element efficiently.
Understanding vectors enables dynamic array management.
Most commonly used STL container for general-purpose data storage.

This program is fundamental for learning STL containers, understanding dynamic arrays, and preparing for advanced data structures and algorithms in C++ programs.

Let us now understand every line and the components of the above program.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Practical Learning Notes for Vector Basics

This C++ program is part of the "STL Containers Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents