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.
1#include <iostream>2#include <vector>3using namespace std;45int main() {6 // Create vector7 vector<int> vec;89 // Add elements10 vec.push_back(10);11 vec.push_back(20);12 vec.push_back(30);13 vec.push_back(40);14 vec.push_back(50);1516 cout << "Vector elements: ";17 for (int i = 0; i < vec.size(); i++) {18 cout << vec[i] << " ";19 }20 cout << endl;2122 // Access elements23 cout << "First element: " << vec.front() << endl;24 cout << "Last element: " << vec.back() << endl;25 cout << "Element at index 2: " << vec.at(2) << endl;2627 // Size and capacity28 cout << "Size: " << vec.size() << endl;29 cout << "Capacity: " << vec.capacity() << endl;3031 // Initialize vector with values32 vector<int> vec2 = {1, 2, 3, 4, 5};33 cout << "\nVector 2: ";34 for (int num : vec2) {35 cout << num << " ";36 }37 cout << endl;3839 // Remove last element40 vec.pop_back();41 cout << "\nAfter pop_back: ";42 for (int num : vec) {43 cout << num << " ";44 }45 cout << endl;4647 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
Create an empty vector<int>.
- 2
push_back 10, 20, 30, 40, 50.
- 3
Print with an index loop.
- 4
Print front, back, at(2), size, and capacity.
- 5
Build vec2 from {1, 2, 3, 4, 5} and print it.
- 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:
Key Features:
Creating Vectors
Empty Vector:
vector<int> vec;
Initialized Vector:
vector<int> vec2 = {1, 2, 3, 4, 5};
What happens here:
Adding Elements
push_back():
vec.push_back(10);
vec.push_back(20);
vec.push_back(30);
What happens here:
Accessing Elements
Methods:
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:
Removing Elements
pop_back():
vec.pop_back(); // Removes last element
What happens here:
When to Use Vectors
Good fits:
Example Scenarios:
Important Considerations
Memory Layout:
Performance:
Automatic Management:
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.