Start learning free

LESSON 105 OF 667 · ARRAYS I

Vector Size in C++

Lesson

We can get the size of a vector using the .size() method:

vector<int> ourArray = {50, 40, 30};

// Printing the size:
cout << ourArray.size() << endl; // Output: 3

// Changing the vector:
ourArray.pop_back();

// Printing the new size:
cout << ourArray.size() << endl; // Output: 2

Using the size

We can use the size to access items from the end of a vector.

Because vectors are 0-indexed, the index of the last item is size - 1:

vector<int> ourArray = {50, 40, 30};

int size = ourArray.size();

// Printing the last item:
cout << ourArray[size - 1] << endl; // Output: 30

// Printing the second to last item:
cout << ourArray[size - 2] << endl; // Output: 40

Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check