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 other items:

  • Complete vacinations required to visit campus or sign up for future terms (instructions)
  • 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 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
  • Food & Housing Resources: free food, meals, temporary and permanent housing
  • COVID-19 Resources and Information: Includes loaner-laptop information
  • Campus WiFi Access
  • Extra credit bonus points for the first student to report a problem

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
  • Notice that Replit is compiling with -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 .at() is called an index
  • Any element is a variable (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 Replit 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 computations, 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 Replit 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 Replit and copy the following program into a text editor.
    #include <iostream>
    #include <vector>
    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 Replit 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: Swapping Two Variables

Sometimes a program must swap values among two variables.

7.6.1: Reviewing Swapping Two Variables

  • Swapping two variables x and y means to assign y's value to x, and x's value to y (Replit):
    // setup
    int x = 42;
    int y = 57;
    int temp;
    // swap sequence to exchange values of x nd y
    temp = x;
    x = y;
    y = temp;
    
  • The idea of this common method is to use a temporary variable
  • A temporary variable is a variable used to store a value for a brief time
Swapping Two Values
x
y
temp
  • Swaps are often performed between two vector elements
  • For example we may reverse the value of a vector as shown in Zybook PA 7.9.4

Reversing a vector

Exercise 7.6: Swapping Two Variables (10m)

In this exercise we swap two elements 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 Replit and copy the following starter code into a text editor.
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main() {
       vector<int> list = { 11, 55, 22, 77, 33 };
    
       // Enter your code here
    
       return 0;
    }
    
  2. Compile your code to make sure you copied it correctly.
  3. Add a for-loop that accesses every index of the list vector and prints every value to the screen followed by a space. When run, the output should look like:
    11 55 22 77 33
    
  4. Add code to swap outermost elements.
  5. Add a second for-loop that prints every value of the vector to the screen. When run, the output should look like:
    11 55 22 77 33
    33 55 22 77 11
    
  6. Now add code to swap the next outermost elements.
  7. Add a third for-loop that prints every value of the vector to the screen. When run, the output should look like:
    11 55 22 77 33
    33 55 22 77 11
    33 77 22 55 11
    
  8. Once satisfied with your code, copy your code into a text editor, save the file as "swap.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.

Deliverables

For this week's exercises we are turning in these files:

Remember that when submitting multiple files to Canvas, you must submit all files in the same session. For instuction on submitting multiple files for an assignment see the Canvas guide on How do I upload a file as an assignment submission in Canvas? section: Submit Assignment.

Lab Introductions

Here are a few tips on how to get started on the labs.

Last Updated: October 07 2021 @22:45:46