What size() returns
size() is a member function of std::vector. It returns the number of elements the vector holds right now:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{4, 8, 15};
std::cout << v.size() << '\n'; // 3
v.push_back(16);
std::cout << v.size() << '\n'; // 4
}
The return type is std::vector<int>::size_type, an unsigned integer type. You rarely need to write that name, since auto works. Calling size() is cheap. For std::vector, the standard requires it to take constant time, so it does not count the elements each time.
It changes as the vector changes
Operations that add or remove elements update the size. These include push_back, pop_back, insert, erase, clear, and resize:
std::vector<int> v;
std::cout << v.size() << '\n'; // 0
v.push_back(1);
v.push_back(2);
std::cout << v.size() << '\n'; // 2
v.pop_back();
std::cout << v.size() << '\n'; // 1
To check for zero elements, empty() reads more clearly than comparing size() with 0:
if (v.empty()) {
std::cout << "no values yet\n";
}
Changing the size on purpose with resize() is covered in How do I resize a vector in C++?
size() versus capacity()
capacity() is how many elements the vector can hold before it needs more memory. The size is never larger than the capacity:
std::vector<int> v;
v.reserve(10);
std::cout << v.size() << '\n'; // 0
std::cout << v.capacity() << '\n'; // 10 or more
reserve() changes the capacity, but the size stays at 0 because no elements were added. The exact capacity an implementation chooses can be larger than the number you asked for, which is why the comment says “10 or more.”
size() versus sizeof
sizeof(v) gives the size of the vector object itself. Every object of type std::vector<int> has the same sizeof, no matter how many elements it holds. It does not count elements, so use v.size() for the count.
Plain arrays also do not carry their size with them, which is why functions often need it passed in separately. For that case, see how to pass an array to a function in c.
Watch out for unsigned math
size() returns an unsigned type, so two mistakes come up often.
First, comparing it with a signed int in a loop can trigger a sign comparison warning. Use an unsigned type that matches:
#include <cstddef>
for (std::size_t i = 0; i < v.size(); ++i) {
std::cout << v[i] << ' ';
}
Second, subtracting 1 from zero wraps around. On an empty vector, size() - 1 is not -1. It becomes a very large unsigned number, so check first:
std::vector<int> empty;
// std::size_t last = empty.size() - 1; // wraps to a very large number, not -1
std::vector<int> v{4, 8, 15};
if (!v.empty()) {
std::size_t last = v.size() - 1; // 2, the index of the last element
}
Summary
size() returns how many elements a vector holds. It changes when elements are added or removed, it is separate from capacity, and it is different from sizeof. Watch the unsigned type in loops and in subtraction. For how a vector gets its starting count, see c vector initialization.