Adding and Removing Elements

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.


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:


We can add elements using .push_back():

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

So now dna would look like:



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


Notice how nothing goes inside the parentheses.

The vector would now look like:


because CTG is removed!

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



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

Add these four strings using .push_back():

  • "kylo"
  • "rey"
  • "luke"
  • "finn"
Folder Icon

Take this course for free

Already have an account?