Finding Vector Size

Sometimes we don't know how many elements a vector has (maybe the vector was created by someone else, or the number of elements changes) and we need to find out.

For this, we use the size() method, which returns the number of elements in the vector. The size() method is used by adding .size() after the vector name. Let's look at an example:

std::vector students = {"Anna", "Boris", "Cecilia", "David", "Eva"};

If we want to find out how many students are in the vector students, we can store the number of elements in a variable and print it:

int numberOfStudents = students.size();
std::cout << numberOfStudents;  // Prints: 5

Or print directly:

std::cout << students.size(); // Prints: 5

Instructions

Using the size() method, print the number of elements in the vector colleagues.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/10

Finding Vector Size | Start Coder