← Back to C++ Course | Chapter 13: STL Containers & Algorithms | Lesson 2 of 15

C++ vector

What is a vector?

A vector is C++'s dynamic array template class: unlike a fixed-size raw array, a vector automatically grows or shrinks as elements are added or removed, managing its own underlying heap memory without you having to call new or delete yourself.

Example: What is a vector?

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums;
	nums.push_back(1);
	nums.push_back(2);
	std::cout << nums.size() << std::endl;
	return 0;
}

Adding and Removing Elements

You add an element to the end of a vector with push_back() and remove the last element with pop_back(); both operations automatically adjust the vector's reported size, so you never manually track how many elements it currently holds.

Example: Adding and Removing Elements

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {1, 2};
	nums.push_back(3);
	nums.pop_back();
	std::cout << nums.size() << std::endl;
	return 0;
}

Accessing Elements

You can access an element with plain index brackets like vec[i], or with the at() method, which is safer because it performs bounds checking and throws an out_of_range exception rather than silently reading invalid memory for a bad index.

Example: Accessing Elements

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {10, 20, 30};
	std::cout << nums[1] << " " << nums.at(2) << std::endl;
	return 0;
}

Vector Capacity vs Size

Size is the number of elements a vector actually currently holds, while capacity is the total memory it has reserved, which is often larger. Vectors deliberately over-allocate capacity in advance so that most push_back() calls don't need to trigger an expensive reallocation.

Example: Vector Capacity vs Size

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {1, 2, 3};
	std::cout << "size=" << nums.size() << " capacity=" << nums.capacity() << std::endl;
	return 0;
}

Iterating over Vectors

You can iterate over a vector's elements with a traditional index-based loop, a range-based for loop for cleaner syntax, or explicit STL iterators — all three work interchangeably and the choice mostly comes down to readability and whether you need the index itself.

Example: Iterating over Vectors

cpp
#include <iostream>
#include <vector>

int main() {
	std::vector<int> nums = {1, 2, 3};
	for (int i = 0; i < nums.size(); i++) std::cout << nums[i] << " ";
	for (int n : nums) std::cout << n << " ";
	std::cout << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.