Chris Gregory

Home Blog LinkedIn Github

C++ Tutorial 4 - Using vector

12/19/2016

Here we will go over vector and some basic usages. A vector is a list of things. To use a vector, we have to write #include <vector> at the top of the file.

#include <vector>
#include <cstdio>

using namespace std;

int main() {
    /* Visual Studio: */ getchar();
    return 0;
}

So now we can use vectors in our program. A vector is a list of things. The type of the elements must be told to the computer to be able to use our vector. Here is how we declare a vector of ints named int_list.

    vector<int> int_list;

To use our list we insert elements and retrieve elements. To insert an element at the end of the vector, write the following code:

    int_list.push_back(42);

Now our vector has one element, 42. To add another element we can repeat the process:

    int_list.push_back(33);

Now our vector has two elements, 42 and 33 in that order. To retrieve elements we use square brackets and an index number. The number starts from 0.

    // retrieve the first element
    int_list[0];

    // retrieve the second element
    int_list[1];

Each element is an integer, so we can interact with each element as one.

    // set the second element to 22
    int_list[1] = 22;

    // ensure the first element has a maximum value of 40
    if (int_list[0] > 40) {
        int_list = 40;
    }

    int index = 0;
    // set the first element to 11
    int_list[index] = 11;

    // print out "Our vector has 2 elements."
    cout << "Our vector has " << int_list.size() << " elements.\n";