YetiCodeCamp - C++ for Beginners

Companion website for the C++ for Beginners YouTube video series.

This is the companion page for the C++ for Beginners Series

Video 11 – C++ Vectors





While we were introduced to vectors in the last video, since this one is dedicated strictly to vectors I thought a quick review was in order. This also helps anyone just coming in straight to this video.

Vectors

Vectors are part of the C++ Standard Template Library or often referred to as simply STL. They are also part of the standard namespace, so you need to prefix the keyword vector with std:: as we do with cout.

Vectors have member functions available to them to make working with them easy.

Function Description
assign() Assigns new values to a vector replacing any existing elements.
at()
Returns the value of the element specified.
back()
Returns the value of the last element in a vector.
begin()
Returns an iterator to the first element in a vector.
capacity() Returns the current memory allocation of a vector.
cbegin()
Returns a const iterator to the first element in a vector.
cend()
Returns an iterator to just beyond the last element of a vector.
clear()
Clears (erases) the contents of a vector.
crbegin()
Returns a const iterator to the first element in a reversed vector.
crend()
Returns a const iterator to the end of a reversed vector.
data() Returns a pointer to the first element in the vector.
emplace()
It inserts a new element just before the position specified.
emplace_back()
It inserts a new element at the end of a vector.
empty()
Boolean check if the vector is empty.
end()
Returns a iterator to the end of a vector.
erase()
Removes one or more elements from a vector.
front() Returns the value of the first element in a vector.
get_allocator() Returns an object to the allocator class used by a vector.
insert() Inserts one or more elements into the vector at the specified position.
max_size() Returns the maximum length of the vector.
operator[]
operator=
pop_back() Deletes the last element of a vector.
push_back() Adds an element to the end of a vector.
rbegin() Returns an iterator to the first element in a reversed vector.
rend() Returns an iterator to the end of a reversed vector.
reserve() Reserves a minimum length of storage for a vector object.
resize() Specifies a new size for a vector.
shrink_to_fit() Reduces the vector capacity by settings it to the current size of the vector.
size() Returns the number of elements in the vector.
swap() Swaps the elements of two vectors.



Vectors are declared with the keyword vector, the data type of the elements, and a name. To be able to use vectors, be sure to #include <vector> at the top of your program.

We do not need to give it a size right away like we did with arrays. Vectors can be resized in memory as needed.


We can initialize vectors upon declaration like in this example:

std::vector<int> myVector = {1,2,3,4,5};


We can declare and initialize vectors at separate times, for example:

std::vector<int> v1;
v1 = {1,2,3,4,5};



Vector Review

We can create a vector to hold the daily high temperatures for the last year, month or week. Here is a simple example showing a vector holding 7 temperature values.

std::vector<double> dailyHigh {72.5, 75.6, 82.3, 85.7, 78.4, 81.9, 88.5};


We can access the contents of the array by referencing the elements index:

std::cout << dailyHigh[3];    //prints out 85.7
std::cout << dailyHigh.at(2); // prints out 82.3


Here is a complete example program that compile and will print out the example dailyHigh vector using a range-based for statement:

#include <iostream>
#include <vector>

int main()
{
    std::vector<double> dailyHigh {72.5, 75.6, 82.3, 85.7, 78.4, 81.9, 88.5};
    for(auto v : dailyHigh)
            std::cout << v << " ";
        std::cout << "\n" <<std::endl;
    return 0;
}



prtVec()

Instead of writing out a bunch of cout statements to display the vector element values all the time, cluttering up the code, let’s utilize a function.

This is a perfect example of when to use a function, when you are going to repeatedly use a certain segment of code over and over again.

Here is the completed print vector function prtVec():

void prtVec(const std::vector<auto> &vec, std::string n="")
{
        // Function takes 2 parameters, vector and optional name
        if (n!="")
            std::cout << n << " is: ";
        for(auto v : vec)
            std::cout << v << " ";
        std::cout << "\n" <<std::endl;
}



Times Table


Final form of the timesTable() function. Remember to declare it above main with:

void timesTable(int x = 10, int y = 10);



Put the actual function definition below main:

void timesTable(int x, int y)
{

    std::string title = "\n\nv4 Times Table\n\n";   // Initial title string with "\n" newlines for positioning

    for(int i=0; i<((y / 2) -1); i++)               // For loop iterating up to y columns / 2 and subtracting one.
        title.insert(2, "\t");                      // Insert a tab at index 2

    std::cout << title;                             // Print the modified title (scaled according to columns)

    std::vector<std::vector<int>> v4(x , std::vector<int>(y));  // Create a vector containing x vectors of size y.

    for(int i=0; i<x; i++)                          // Standard for-loop to iterate through and fill vector elements with i*j
        for (int j=0; j<y; j++)
            v4[i][j] = (j+1) * (i+1);               // Need to add one to account for 0 index

                                                    // Print out vector, just as we did for our arrays using range-based for statement
    for(const auto &x : v4)                         // Iterate through "rows" or vector 'x' (there are 10 vectors)
    {
        for(const auto &y : x)                      // Iterate through "cols" or elements in vector x
            std::cout << y << "\t";
        std::cout << "\n\n";
    }
}