Start learning free

LESSON 100 OF 667 · ARRAYS I

Vector in C++

Lesson

A big limitation of static arrays in C++ is the fact that once the array is created, it has a fixed size.

The vector overcomes this limitation by having variable size and allowing for elements to be added or removed.


Creation:

You start a vector declaration by using the vector keyword, then writing the type of the elements inside <>, along with the name of the vector:

vector<string> sandwich;

This code creates an empty vector named sandwich where each item is a string.


Initialization I:

You can also initialize a vector at declaration by using the = operator with an opening bracket, end it with a closing bracket, and put a comma between each entry, like this:

vector<string> sandwich = {"peanut butter", "jelly", "bread"};

We created a vector named sandwich which consits of 3 items: "peanut butter", "jelly" and "bread".


Initialization II:

Another way of initializing a vector at declaration is by providing the number of elements and their initial value, like this:

vector<string> animals(5, "cat");

We created a vector named animals which consits of 5 "cat" items.


Assignment
Follow the Coding Tutorial and let's create some vectors!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check