C++ Vector Magnitude

Steven Cowie picture Steven Cowie · Nov 13, 2017 · Viewed 11.7k times · Source

I have been tasked with making a vector magnitude function in C++ as part of a maths library for a class project, however I am unsure how to go about this, if someone could recommend some pages to read and or give me some help that would be great

Edit: My C++ knowledge isn't that great, I'm looking for pages to help me learn how to do functions for vectors

Answer

Paul Floyd picture Paul Floyd · Nov 13, 2017

A quick google comes up with

magnitudes

As this is a class project I'll let you read the link rather than giving full details here.

You may want to read up on using vectors, for instance here.

Personally I prefer to use C++ standard algorithms where possible. You can do this sort of thing quickly and efficiently with std::accumulate.

#include <iostream>
#include <vector>
#include <numeric>
#include <string>
#include <functional>

int main()
{
    std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    double ssq = std::accumulate(v.begin(), v.end(),
                                    0.0,
                                    /* add here */);

    std::cout << "ssq: " << ssq << '\n';
}

The line marked /* add here */ is where you need to add an operator that takes the current running sum of squares and the next value to add to it, and returns the new running sum of squares.

Alternatively, you could just write a for loop

double ssq = 0.0;
std::vector<double> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto e : v)
{
    // calculate sum of squares here
}