Cheat Sheets are in BETA. Give us your feedback.

Index

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 its index, like name[index].

Note: The first element in a vector or an array has an index of 0.

std::vector<double> order = {3.99, 12.99, 2.49}; // what's the first element? std::cout << order[0]; // what's the last element? std::cout << order[2];

.size() Vector Function

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

std::vector<std::string> peeps; peeps.push_back("michael"); peeps.push_back("dwight"); peeps.push_back("pam"); peeps.push_back("jim"); std::cout << peeps.size(); // outputs 4

Vectors

In C++, a vector is a dynamic list of items, that can shrink and grow in size. It is created using std::vector<type> name; and it can only store values of the same type.

All the elements are stored in contiguous locations, which means that they can be accessed with an index. The first index in a vector is 0.

To use vectors, it is necessary to #include the vector library.

#include <iostream> #include <vector> int main() { std::vector<int> grades(3); grades[0] = 90; grades[1] = 86; grades[2] = 98; // display 1st element std::cout << grades[0]; // display 2nd element std::cout << grades[1]; }

Adding or Removing Elements

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
std::vector<std::string> wishlist; // add two items wishlist.push_back("oculus"); wishlist.push_back("tele"); // remove an item wishlist.pop_back(); std::cout << wishlist.size(); // will print 1