Mar 06 In-Class

Mar 06 In-Class#

Note

There are no wrong answers. This is for participation credit, and is intended to let me know how well we understand the material at this point.

Access the form: https://forms.gle/AdFzxiuRLXWZjnF87

Question 1#

Consider the following code:

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

for (auto e : vec) {
    // do something with e
}

As written, in the loop we cannot modify the value of e. How do we change this to let us modify e?

solution

We need to use a reference when accessing the element of the vector. This means modifying the loop to be:

for (auto &e : vec) {
    // do something with e
}

Question 2#

Consider the following struct representing a 3D Cartesian mathematical vector (with \(x\), \(y\), and \(z\) components):

struct MathVector {
    double x{};
    double y{};
    double z{};
};

How do you create a MathVector called v and initialize it with \((x, y, z) = (1, 2, 3)\)?

solution

We would do any of the following:

MathVector v{1, 2, 3};
MathVector v{.x=1, .y=2, .z=3};
MathVector v;
v.x = 1;
v.y = 2;
v.z = 3;