Examples of Using vector

Examples of Using vector#

Small-angle approximation example#

In your homework, you looked at the small angle approximation for a variety on angles. We can write that code a lot more compactly now with loops:

Listing 34 sine_loop.cpp#
#include <iostream>
#include <cmath>
#include <numbers>
#include <vector>
#include <format>

int main() {

    double pi = std::numbers::pi;

    std::vector<double> angles_deg{5.0, 10.0, 20.0, 40.0};

    std::cout << std::format("{:10} : {:10} {:10} {:10}\n",
                             "angle (d)", "angle (r)", "sine", "err");

    for (auto a : angles_deg) {

        double angle_rad = a * pi / 180;
        double sine = std::sin(angle_rad);
        double err = std::abs(sine - angle_rad);

        std::cout << std::format("{:10.2f} : {:10.3f} {:10.5f} {:10.5g}\n",
                                 a, angle_rad, sine, err);

    }
}

Notice that we also use std::format here and set the column widths to give a nice table output.

Averaging#

Let’s see how to compute the average of a vector’s elements.

Listing 35 average.cpp#
#include <iostream>
#include <vector>

int main() {

    std::vector<double> vec{1.0, 2.2, 10.5, 21.3, 25.4, 6.6, 4.2};

    double sum{};
    for (auto e : vec) {
        sum += e;
    }

    double avg = sum / vec.size();

    std::cout << "The average is: " << avg << std::endl;

}

Important

We need to initialize sum to 0.0 here (we did it using {}), because we are adding to it in the loop. If we didn’t initialize it, its value would be undefined at the start.