C++ vector
In this page:
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?
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {10, 20, 30};
std::cout << nums[1] << " " << nums.at(2) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: