Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Vector Basics in C++

Learn C++ vector basics: push_back, [] versus at(), front and back, size versus capacity, initializer lists, range-based for loops, and pop_back, with output.

BeginnerSTL Containers ProgramsExample 1 of 10
vector-basics.cpp
1#include <iostream>
2#include <vector>
3using namespace std;
4
5int main() {
6 // Create vector
7 vector<int> vec;
8
9 // Add elements
10 vec.push_back(10);
11 vec.push_back(20);
12 vec.push_back(30);
13 vec.push_back(40);
14 vec.push_back(50);
15
16 cout << "Vector elements: ";
17 for (int i = 0; i < vec.size(); i++) {
18 cout << vec[i] << " ";
19 }
20 cout << endl;
21
22 // Access elements
23 cout << "First element: " << vec.front() << endl;
24 cout << "Last element: " << vec.back() << endl;
25 cout << "Element at index 2: " << vec.at(2) << endl;
26
27 // Size and capacity
28 cout << "Size: " << vec.size() << endl;
29 cout << "Capacity: " << vec.capacity() << endl;
30
31 // Initialize vector with values
32 vector<int> vec2 = {1, 2, 3, 4, 5};
33 cout << "\nVector 2: ";
34 for (int num : vec2) {
35 cout << num << " ";
36 }
37 cout << endl;
38
39 // Remove last element
40 vec.pop_back();
41 cout << "\nAfter pop_back: ";
42 for (int num : vec) {
43 cout << num << " ";
44 }
45 cout << endl;
46
47 return 0;
48}

Sample Output

Capacity: 8

GCC's libstdc++ doubles 1→2→4→8, so 8 slots exist for 5 elements.

After pop_back: 10 20 30 40

The last element, 50, was removed.

In this one

  • How push_back grows a vector
  • The difference between [] and at()
  • Why size and capacity are different numbers
  • How to loop with an index or a range-based for

How it works

  1. 1

    Create an empty vector<int>.

  2. 2

    push_back 10, 20, 30, 40, 50.

  3. 3

    Print with an index loop.

  4. 4

    Print front, back, at(2), size, and capacity.

  5. 5

    Build vec2 from {1, 2, 3, 4, 5} and print it.

  6. 6

    pop_back and print what is left.

Edge cases

Index out of range

Use vec.at(10) and then vec[10].

at() throws std::out_of_range, which you can catch. [] skips the check, so the result is undefined behavior.

front() on an empty vector

Call vec.front() after clearing the vector.

Calling front, back, or pop_back on an empty vector is undefined. Check empty() first.

Different capacity

Compile with MSVC instead of GCC.

The growth factor differs, so the capacity line may say 6 instead of 8. Everything else matches.

What's going on

A vector is a resizable array. It keeps its elements next to each other in memory, like a plain array, but it grows by itself when you add more. This program builds one, reads from it in several ways, and shrinks it again.

vector<int> vec; starts empty. Each push_back adds an element at the end, so after five calls the vector holds 10 20 30 40 50.

The first loop uses an index and vec[i]. The square brackets do no bounds check, so vec[10] would be undefined behavior. vec.at(2) reads the same kind of slot but checks the index and throws std::out_of_range when it is too large. front() and back() are shortcuts for the first and last element.

size() is how many elements are stored (5). capacity() is how many fit before the vector must allocate a bigger block. When it runs out of room, the vector allocates a larger block (often about double), moves the elements across, and frees the old one. The sample shows 8, which is what GCC's library gives after five push_backs; Visual C++ grows by 1.5× and prints 6. Capacity is an implementation detail, so do not rely on the exact number.

vector<int> vec2 = {1, 2, 3, 4, 5}; fills a vector from an initializer list, and the range-based for (int num : vec2) visits every element without an index.

Finally pop_back() removes the last element (50). It does not return it, so read back() first if you need the value.

The headers come first. <iostream> is there because it provides cout and cin for input/output operations. <vector> is there because it provides vector container class. Leave one out and the compiler stops at the first name it does not recognize.

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)

Creating Vectors

Empty Vector:

vector<int> vec;

Initialized Vector:

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

What happens here:

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

Adding Elements

push_back():

vec.push_back(10);

vec.push_back(20);

vec.push_back(30);

What happens here:

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

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)

Size and Capacity

Size:

vec.size() // Number of elements

Capacity:

vec.capacity() // Allocated memory size

What happens here:

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

Removing Elements

pop_back():

vec.pop_back(); // Removes last element

What happens here:

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

When to Use Vectors

Good fits:

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

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

return 0;

return 0; closes main and tells the operating system the program finished without an error.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

After five push_backs, which is guaranteed?

Pick an answer to check it.

Question 2

What does vec.at(99) do on a 5-element vector?

Pick an answer to check it.

Questions people ask

When should I use a vector instead of an array?

Almost always when the size is not fixed at compile time. Use std::array for a fixed size.

How do I avoid repeated reallocations?

Call vec.reserve(n) up front when you know roughly how many elements are coming.

Why does the compiler warn about i < vec.size()?

size() returns an unsigned size_t and i is a signed int. Use size_t i or a range-based for loop.