7. Vectors

Review Topics


General Information

Housekeeping

  • Make sure you follow along with this page linked in Canvas
  • Please keep your microphone off unless you are asking a question
  • Please turn on camera if you can (optional)
  • Use chat if you would like to comment or ask questions

Announcements

See Announcements link in Canvas to keep up with what is going on. Here are a few for review:

  • Cabrillo College will now allow students to select the P/NP option by the grade deadline for the term--ends in December
  • Repl.it moving to replit.com on Friday--if problems try these alternate sites:
  • Remember that PAs and the Individual Readiness Assurance Quiz are due before class on Tuesday.
  • Remember to post in the Pair programming partners discussion group if you need a partner
  • Remember that the exercises from this page are due Sunday at 9:00pm.
  • Remember that CAs, Labs, and Class Exercises may be completed up to two days late but with a 10%/day penalty.
  • Remember that some lab solutions are posted in Canvas Modules
  • Free Fresh Market schedule: free fresh fruits and vegetables
  • Food & Housing Resources: free food, meals, temporary and permanent housing
  • COVID-19 Resources and Information: Includes loaner-laptop information
  • Campus WiFi Access
    • Aptos: Parking lots K and L on this Cabrillo Aptos Map
    • Watsonville: Parking lot at Watsonville Center

Homework Help

7.1: Readiness Assessment Quizzes

  • Reading and participation activities are due before the first class meeting of the week
  • Quizzes assess the comprehension of the reading and participation activities

Quiz Part 1: Individual Readiness Assessment

  • Complete this quiz solo to assess your reading comprehension and readiness
  • Must take this quiz before the first class meeting of the week to ensure you are ready for the team quiz
  • Quiz is open book and notes but timed
  • Highest score is counted so take the quiz multiple times

Quiz Part 2: Team Readiness Assessment (20m)

  • Must attend the class meeting to take this quiz
  • Login to Canvas
  • Will move to breakout rooms with your team
  • Make sure you have the access code for the exam
  • Openly discuss what you believe to be the best answers for the questions
  • Decide how to agree on the answers
    • Strive to reach a consensus on quiz answers
    • If no consensus, work it out as you and others in your group see fit
  • Turn in the quiz as a group
  • Each group member will receive the same score
  • Return to the main meeting room when finished

Quiz Appeals

  • After completing the team quiz, team members may appeal an answer
  • Appeals can be based on two criteria:
    1. Question is factually wrong

      Appeal must included citations to sources of information that document or support an alternative answer. Team may access reference materials during the appeal.

    2. Question is confusing based on it's wording

      Appeal must include an appropriate rewrite of questions or answers that you interpret as ambiguous or confusing.

  • Work with teammates to develop and write any appeals
  • Team has up to 24 hours after the quiz to email appeal to instructor
  • If appeal is granted, only the teams that submitted appeal gets credit

7.2: Declaring and Accessing Vectors

A vector is a way to maintain a list of items in a program, like people maintain a grocery list.

7.2.1: Reviewing Vector Declarations and Access

  • Often times we need to process a list of data
  • Vectors offer a convenient way to process such a list
  • The vector data type is defined in the standard library vector:
    #include <vector>
    using namespace std;
    
  • As an example, the following is the definition of a vector named scores that holds 10 values of type int:
    vector<int> scores(10);
  • This code creates 10 contiguous elements in memory that each hold an int

    list

  • Another way to declare a vector is with a list of values to store
    vector<int> scores = { 90, 95, 97, 89, 98 }; // 5 values
    
  • The above creates a vector with 5 elements
  • However, to compile a vector with this approach you must use C++-11 or later
    g++ -Wall -Wextra -Wpedantic -std=c++11 -o main main.cpp
    
  • Notice that Replit in its compiling uses -std=c++17
    clang++-7 -pthread -std=c++17 -o main main.cpp
    

Accessing Vector Elements

  • Once we have a vector, we specify which element to use with the at() function:
    scores.at(4) = 98;
  • The number inside the brackets is called an index
  • Any element is a variable of the vector data type (int in this case) and can be used like a variable:
    cout << scores.at(4) << endl;
  • The index of a vector can be any integer value, which means we may use variables or expressions to specify the index
  • This lets us use the counter variable of a loop as the vector index, like:
    for (int i = 0; i < 5; i++) {
        cout << scores.at(i) << endl;
    }
    

Vector Size

  • We can find the size of a vector by calling the size() function
    vector<int> scores = { 90, 95, 97, 89, 98 };
    cout << scores.size() << endl;
    
  • The size() function is useful in counting loops:
    unsigned i;
    for (i = 0; i < scores.size(); i++) {
        // do something with scores.at(i)
        cout << scores.at(i) << endl;
    }
    
  • The unsigned data type is shorthand for unsigned int

Exercise 7.2: Vector Basics (12m)

In this exercise we create a vector.

Remember to verify your code by compiling after each step.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Inside main(), add a statement to define a vector of type double named temp along with a list of five (5) values of your choice.
  3. Compile your code to make sure it has correct syntax.
  4. Print element 0 like:
    cout << "Element 0: " << temp.at(0) << endl;
    
  5. Compile your code to make sure it has correct syntax. Run the code and verify you see the first value of your vector.
  6. Add a for-loop that accesses every index of the temp vector and prints every value to the screen like:
    for (unsigned i = 0; i < temp.size(); ++i) {
        cout << temp.at(i) << endl;
    }
    
  7. Compile your code to make sure it has correct syntax. Run the code and verify you see the all the values of your vector displayed.
  8. Declare a summing variable named total before the loop and initialize the variable to zero (0).
  9. Inside the loop, add the indexed temp.at(i) value to total every time the loop iterates.
        total = total + temp.at(i);
    
  10. After the loop completes, print the ending value of total.
    cout << "total: " << total << endl;
    
  11. Compile your code to make sure it has correct syntax. Run the code and verify you see a correct value for total.
  12. Once satisfied with your code, copy your code into a text editor, save the file as "templist.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

7.3: Iterating Vectors

An important programming skill to master is iterating through vectors using loops.

7.3.1: Reviewing Vector Iteration

  • Iterate means to make repeated use of a computational procedure, applying it each time to the result of the previous application
  • Many uses of vectors involve iteration such as
    • Finding a particular value
    • Finding a minimum or maximum value
    • Summing or averaging values
  • To find some quantity in a vector, we iterate through the vector with a for loop
  • For some iteration computation, like summing or averaging, we update a variable each time through the loop
    vector<int> scores = { 90, 95, 97, 89, 98 };
    int sum = 0;
    for (unsigned i = 0; i < scores.size(); i++) {
        sum = sum + scores.at(i);
    }
    cout << "Sum=" << sum << endl;
    cout << "Average=" << sum / scores.size() << endl;
    
  • Other iterative computations require one or more if statements to test for a condition
    vector<int> scores = { 90, 95, 97, 89, 98 };
    int value;
    for (unsigned i = 0; i < scores.size(); i++) {
        if (test condition) {
            value = scores.at(i);
        }
    }
    cout << value << endl;
    
  • Then inside the if statement the code updates the value

Exercise 7.3: Iterating Vectors (10m)

In this exercise we use iteration for common computations on a vector.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Inside main(), add a statement to define a vector of type double named temp along with a list of five (5) randomly chosen values.
  3. Next, declare variables of type double to store the sum, minimum and maximum values of the vector, like:
    double sum = 0;
    double min = temp.at(0);
    double max = temp.at(0);
    

    Notice we initialize the sum to 0 and the min and max to the first value of the vector. Add a comment after each variable declaration to explain why it is initialized in that way.

  4. Add a for-loop that accesses every index of the temp vector and adds it to the sum, like:
    for (unsigned i = 0; i < temp.size(); ++i) {
        sum = sum + temp.at(i);
    }
    
  5. After the for loop, print the sum, average, minimum and maximum values like:
    cout << "Sum=" << sum << endl;
    cout << "Average=" << sum / temp.size() << endl;
    cout << "Minimum=" << min << endl;
    cout << "Maximum=" << max << endl;
    
  6. Inside the for loop, after the sum computation, add an if statement to test for a minimum value, like:
    if (min > temp.at(i)) {
        min = temp.at(i);
    }
    
  7. Similarly, add an if statement to test for a maximum value.
  8. Compile your code to make sure it has correct syntax. Run the code and verify you see a correct value for sum, average, minimum and maximum.
  9. Once satisfied with your code, copy your code into a text editor, save the file as "iterate.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

7.4: Multiple Vectors

Programmers commonly use multiple same-sized vectors to store related lists.

7.4.1: Reviewing Multiple Vectors

  • Suppose we want to process a series of product data like name, price, quantity, etc.
  • Here is some sample data:
    Name Price
    Milk 3.95
    Bread 2.99
    Cheese 3.95
  • We want to be able to display the data and process the items in various ways
  • One possibility is to create multiple vectors as shown in the diagram below
  • Each slice (name, price, etc.) contains data that must be processed together and kept in order together

A Slice in Multiple Vectors

Two Vectors Storing Related Data
Name Vector
 
 
 
 
Bread
 
 
 
 
 
Price Vector 
 .at(0)
 .at(1)
 .at(2)
 .at(3)
2.99.at(4) Slice
 .at(5)
 .at(6)
 .at(7)
 .at(8)
 .at(9)

Accessing Data in Multiple Vectors

  • To access data in multiple vectors, we search one vector for a desired values
  • To search each element we use a for-loop
  • Inside the for-loop we put an if-statement to select the desired value
  • After finding the desired value we use the index to access the other elements in the slice
  • The following is a simple example of multiple vectors

Example of Multiple Vectors

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<string> product = { "Apple", "Bread", "Cheese", "Milk", "Orange" };
    vector<double> price = { 1.62, 2.99, 4.95, 3.95, 1.10 };
    cout << "Enter a product name: ";
    string name;
    cin >> name;
    for (unsigned i = 0; i < product.size(); i++) {
        if (product.at(i) == name) {
            cout << name << " at " << i << " costs " << price.at(i) << endl;
        }
    }

    return 0;
}

Exercise 7.4: Iterating Multiple Vectors (15m)

In this exercise we explore the use of multiple vectors.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    using namespace std;
    
    int main() {
        // add code here
    
        return 0;
    }
    
  2. Next we add two vectors to the program with parallel data
    vector<string> area = { "Aptos", "Capitola", "Felton",
        "Santa Cruz", "Watsonville" };
    vector<int> particleCounts = { 37, 39, 51, 53, 42 };
    

    Note: particle counts were from PurpleAir readings during the 2020 fire.

  3. Now add statements to let the user input a location. Notice that locations may have spaces in names so we must use getline().
  4. Now we want to add a for loop to look up the location in the area vector. Inside the for loop we place an if statement to test for a match between a vector element for area and the location entered by the user.
  5. When the program finds a match between the location and the area, we print the particle readings for the area.
    cout << location << " particle readings are "
         << particleCounts.at(i) << endl;
    
  6. Compile and run your code to make sure you completed the program correctly. When you run the program, the output should look like:
    Enter a location: Aptos
    Aptos particle readings are 37
    
  7. Once satisfied with your code, copy your code into a text editor, save the file as "particulates.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

7.5: Back of the Vector

A vector has functions for working at the back (last element) of a vector, as shown in the following table.

Common vector functions at the back
back() int back(); Returns vector's last element. Vector is unchanged.
pop_back() void pop_back(); Removes the last element.
push_back() void push_back(const int newVal); Append new element having value of newVal.

7.5.1: Reviewing Back of the Vector Functions

  • Defining a vector without an initial size creates an empty vector with no space for elements:
    vector<int> scores;
    cout << scores.size() << endl;
    
  • A vector of size 0 is actually useful because we can change the size of a vector
  • If we know the size of data we are working with, then we should declare the size when we define the vector
  • However, we do not always know the size of data we will work with
  • For example, a user may decide how many data items to enter into the program
  • In this case, we can start with an empty vector and grow the vector whenever we add another element
  • The push_back() function resizes the vector by adding one element to its end:
    scores.push_back(42);
    cout << scores.size() << endl;
    
  • Another member function, back(), returns the last value in a vector
    cout << scores.back() << endl;
    
  • Yet another function, pop_back(), removes the last element of a vector, shrinking its size by one:
    scores.pop_back();
    cout << scores.size() << endl;
    
  • The example program listed below shows how to collect data with a variable number of elements

Collecting and Displaying a Variable Number of Data Items

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> scores;

    cout << "Enter scores (-1 to quit):\n";
    int value = 0;
    while (value != -1) {
        cin >> value;
        if (value != -1) {
            scores.push_back(value);
        }
    }

    cout << "You entered:\n";
    for (unsigned i = 0; i < scores.size(); i++) {
        cout << scores.at(i) << endl;
    }

    return 0;
}

Exercise 7.5: Adding Elements with push_back() (12m)

In this exercise we add and remove elements from the end of a vector.

For this exercise we break into teams. Within the team, work with each other to develop a solution. When the team has finished, choose one member to show your solution to the class by sharing your screen. The instructor will ask one team to share their solution.

Specifications

  1. Start Repl.it and copy the following program into a text editor.
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
        // Enter your code here
    
        return 0;
    }
    
  2. Inside main(), add a statement to define a vector of type double named temp along with a list of five (5) randomly chosen values.
  3. Compile your code to make sure it has correct syntax.
  4. Add a for-loop that accesses every index of the temp vector and prints every value to the screen followed by a space. When run, the output should look like the following, depending on the numbers chosen.
    12.3 23.4 34.5 45.6 56.7
    
  5. Add two more elements to the temp vector using the push_back() function. For example, here is how to add one element:
    temp.push_back(42.1);
    
  6. Next add statements to print the vector size and the last element, like:
    cout << "size: " << temp.size() << endl;
    cout << "last: " << temp.back() << endl;
    
  7. After this, add another copy of the for-loop from step 4. When run, the output should look like the following, depending on the numbers chosen.
    12.3 23.4 34.5 45.6 56.7
    size: 7
    last: 24.6
    12.3 23.4 34.5 45.6 56.7 42.1 24.6
    
  8. Now remove the last element using pop_back() and then print the size and last element again:
    temp.pop_back();
    cout << temp.size() << endl;
    cout << temp.back() << endl;
    
  9. After this, add yet another copy of the for-loop from step 4. When run, the output should look like the following, depending on the numbers chosen.
    12.3 23.4 34.5 45.6 56.7
    size: 7
    last: 24.6
    12.3 23.4 34.5 45.6 56.7 42.1 24.6
    size: 6
    last: 42.1
    12.3 23.4 34.5 45.6 56.7 42.1
    
  10. Once satisfied with your code, copy your code into a text editor, save the file as "pushback.cpp", and submit the file to Canvas with the rest of the exercise files for the week.

When finished developing your code click hereClick to show answer to verify. Code need not look exactly the same. After you have completed your own program, reviewing another is often helpful in learning how to improve your programming skills.

7.6: Installing a compiler

Using an online compiler like replit is convenient but problematic when you need to work offline. In addition, by compiling on your own computer you can run your programs on you own computer too! In this section we look at how to install a compiler on your computer.

7.6.1: Recommendations for installing a compiler on your computer

For Windows and Linux, install Code::Blocks

For Macintosh use the free Xcode supplied by Apple; see: How to Install g++ on the Mac.

If problems installing can try one of the other IDEs: CLion, Eclipse, Visual Studio Code. Optionally, use a terminal window and any text editor.

7.6.2: Installing a Terminal Window

If you want to experiment with the Terminal:

Can use any text editor for writing code when using a terminal window.

In addition, can use an editor within a terminal windows: nano, vim, emacs

  • nano: easy to use
  • vim--VI Improved--more full featured
  • emacs--extensible and customizable

Usually available in a Linux/Mac terminal window or Cygwin on Windows.

Exercise 7.6: Installing a compiler (25m)

In this exercise you install a compiler on your computer.

For this exercise we break into teams based on computer type. Within the team, work with each other to install a compiler. For this exercise, self-select your room based on computer type. Match the following room numbers with the computer type:

  1. Reserved
  2. Linux
  3. Apple
  4. and higher: Windows

The first room is reserved for use by instructor invitation only.

Specifications

  1. Depending on you computer type, install a compiler using one of these methods:
    1. How to Install Code::Blocks on Linux
    2. Macintosh: install Xcode for the Mac; see How to Install g++ on the Mac.
      If you cannot install Xcode, try installing the free version of Visual Studio Code instead:
      1. Visual Studio Code: Download the application
      2. C/C++ for Visual Studio Code: setting up VS code for use with C++
      3. Using Clang in Visual Studio Code: setting up VS code for the Mac
    3. How to Install Code::Blocks on Windows
  2. Help those who have difficulties and get help from a classmate, tutor or the instructor as needed.

    If you cannot install, don't panic! You can still use the online tools. However, installing a compiler on your own computer gives you freedom from online compilers and the ability to run your apps on your own computer.

  3. Briefly describe the technical parts of your installation experience in a file named install.txt. Describe all of these parts:
    1. What you installed (example: Cygwin)
    2. Type of computer you installed the compiler on (example: Windows Surface)
    3. What step(s) of the instructions were difficult (example: step 9. Select packages)
    4. Any problems you overcame (example: had to upgrade OS to install Xcode)
    5. How you tested the installation (example: compiled and ran hello.cpp)
  4. When finished installing a compiler, verify your installation by compiling and running the hello.cpp program.
  5. Turn in the executable program you create to Canvas (as hello.exe on Windows and hello on Linux or Mac) and your install.txt file with the rest of the exercise files for the week.

    You may need to zip your executable to submit to Canvas.

Last Updated: March 18 2021 @05:09:26