Hello, I am trying to convert a double array parameter into a vector. I don't have a very full understanding of vectors and I couldn't comprehend the documentation ( http://www.cplusplus.com/reference/vector/vector/ ). I *DID* reference this earlier post:
but I am still unsure. So FROM the 2nd code block, I should change it TO something like this 1st code block?
double calcStdDev(vector<double> data, int size)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
double calcStdDev(double data[], int size)
{
int i;
double sum = 0.0, avg, stdDev = 0.0;
// calculate sum of data
for (i = 0; i < size; ++i)
{ sum += data[i]; }
// calculate average
avg = sum / size;
// calculate and return the standard deviation
for (i = 0; i < size; ++i)
{ stdDev+= pow(data[i] - avg, 2); }
return sqrt(stdDev/ size);
}
Vectors keep track of their size, so you don't need to pass that separately. And you should pass it as a const reference instead of as a copy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
double calcStdDev(const vector<double>& data)
{
// calculate sum of data
double sum = 0.0;
for (size_t i = 0; i < data.size(); ++i)
sum += data[i];
// calculate average
double avg = sum / data.size();
// calculate and return the standard deviation
double stdDev = 0.0;
for (size_t i = 0; i < data.size(); ++i)
stdDev += (data[i] - avg) * (data[i] - avg);
return sqrt(stdDev / data.size());
}
Vectors also have begin() and end() iterators and therefore can be used in a range-based for loop:
1 2 3 4 5 6 7
double sum{};
for (auto d: data) sum += d;
double avg = sum / data.size();
double stdDev{};
for (auto d: data) stdDev += (d - avg) * (d - avg);