How to Find Size of Vector in C++: Syntax and Examples
In C++, you can find the size of a
std::vector by using its size() method, which returns the number of elements currently stored. For example, vec.size() gives the count of elements in the vector vec.Syntax
The size() method is called on a vector object to get the number of elements it contains.
vector_name.size(): Returns the number of elements in the vector as asize_ttype.
cpp
std::vector<int> vec = {1, 2, 3}; size_t count = vec.size();
Example
This example creates a vector of integers, adds some elements, and prints the size using size().
cpp
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {10, 20, 30, 40}; std::cout << "The size of the vector is: " << numbers.size() << std::endl; return 0; }
Output
The size of the vector is: 4
Common Pitfalls
Some common mistakes when finding vector size include:
- Using
sizeof(vector)which returns the size of the vector object in memory, not the number of elements. - Confusing
capacity()withsize().capacity()shows allocated space, not actual element count.
cpp
/* Wrong way: sizeof returns bytes, not element count */ std::vector<int> v = {1, 2, 3}; // size_t wrong_size = sizeof(v); // Incorrect /* Right way: use size() method */ size_t correct_size = v.size();
Quick Reference
| Method | Description |
|---|---|
| size() | Returns the number of elements in the vector |
| capacity() | Returns the number of elements the vector can hold without reallocating |
| empty() | Returns true if the vector has no elements |
Key Takeaways
Use the vector's size() method to get the number of elements it contains.
Do not use sizeof() to find the number of elements in a vector.
size() returns a size_t type representing the element count.
capacity() is different from size() and shows allocated space, not element count.
Check if a vector is empty with the empty() method.