Learn

Often, we start with a vector that’s either empty or a certain length. As we read or compute data we want, we can grow the vector as needed.

.push_back()

To add a new element to the “back”, or end of the vector, we can use the .push_back() function.

For example, suppose we have a vector called dna with three letter codes of nucleotides:

std::vector<std::string> dna = {"ATG", "ACG"};

It would look like:

1

We can add elements using .push_back():

dna.push_back("GTG"); dna.push_back("CTG");

So now dna would look like:

2

.pop_back()

You can also remove elements from the “back” of the vector using .pop_back().

dna.pop_back();

Notice how nothing goes inside the parentheses.

The vector would now look like:

3

because CTG is removed!

Note: If you have programmed in other languages, be aware that .pop_back() has no return value in C++.

Instructions

1.

Inside the code editor, we have a std::string vector.

Add these four strings using .push_back():

  • "kylo"
  • "rey"
  • "luke"
  • "finn"

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?