Key Concepts

Review core concepts you need to learn to master this subject

Vector Type in C++

During the creation of a C++ vector, the data type of its elements must be specified. Once the vector is created, the type cannot be changed.

Vector Index in C++

In C++, an index refers to an element’s position within an ordered list, like a vector or an array.

A specific element in a vector or an array can be accessed using the square bracket [] operator, like name[index].

Note: The index starts from the value 0.

.size() Vector Function in C++

In C++, the .size() function can be used to return the number of elements in a vector, like name.size().

Vectors in C++

In C++, a vector is a dynamic array, which can shrink and grow in size. All the elements are stored in contiguous locations, so they can be accessed with an index. The index starts with the value 0.

To use vector, you must #include the vector library.

.push_back() / .pop_back()

In C++, the following functions can be used to add and remove an element in a vector:

  • .push_back() to add an element to the “end” of a vector
  • .pop_back() to remove an element from the “end” of a vector
Lesson 1 of 1
  1. 1
    To do just about anything of interest in a program, we need a group of data to work with. For example, our program might need: - A list of Twitter’s trending tags - A set of payment options for a…
  2. 2
    The std::vector lives in the header. So first, we need to add this line of code at the top of the program: #include For review, #include is a preprocessor directive that tells the compiler t…
  3. 3
    Now we know how to create a vector, we can also initialize a vector, giving it values, as we are creating it in the same line. For example, instead of just creating a double vector named location:…
  4. 4
    Now that we have a vector, how do we access an individual element? This is where index comes into play. An index refers to an element’s position within an ordered list. Vectors are 0-indexed, me…
  5. 5
    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 “…
  6. 6
    not only stores the elements; it also stores the size of the vector: size The .size() function returns the num…
  7. 7
    So what happens when you want to change each of the values within a vector? You can use a for loop! For example, suppose we have an int vector that looks like this: ![1](…
  8. 8
    Congratulations! You have learned about how to store groups of data into vectors in C++.  Here are some of the things that we learned: - Vectors are a sequence of elements that you can access by…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo