Learn
Vectors
.size()

<std::vector> not only stores the elements; it also stores the size of the vector:

size

The .size() function returns the number of elements in the vector.

For example, suppose we have a std::string vector with Sonny’s grocery list:

std::vector<std::string> grocery = {"Hot Pepper Jam", "Dragon Fruit", "Brussel Sprouts"};

It should look something like this:

https://content.codecademy.com/courses/learn-cpp/vectors/size1.png

  • The string at index 0 is "Hot Pepper Jam".
  • The string at index 1 is "Dragon Fruit".
  • The string at index 2 is "Brussel Sprouts".
std::cout << grocery.size() << "\n";

will return

3

Notice how nothing goes in the parentheses.

Instructions

1.

Add a few more items to the grocery list using .push_back().

Print the size of grocery using .size().

Is it the same as you expected?

Folder Icon

Take this course for free

Already have an account?