Euclidean distance between std::vectors

Hello People,

I am stuck with a problem here, so I need your wisdom.

The following is a template for computing the euclidean distance between two std::vectors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Example program
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <vector>
#include <functional>

using namespace std;

// Computes the distance between two std::vectors
template <typename T>
double	vectors_distance(const std::vector<T>& a, const std::vector<T>& b)
{
	std::vector<double>	auxiliary;

	std::transform (a.begin(), a.end(), b.begin(), std::back_inserter(auxiliary),//
	[](T element1, T element2) {return pow((element1-element2),2);});
	auxiliary.shrink_to_fit();

	return  sqrt(std::accumulate(auxiliary.begin(), auxiliary.end(), 0));
} // end template vectors_distance

int main()
{
std::vector<double> v1 = {0.1,0.3,0.4};
std::vector<double> v2 = {-0.1,-0.3,-0.4};

std::cout << vectors_distance(v1,v2) << "\n";
}


There seems to be something wrong with the precision here, because the exposed example has an output of 0!

What is the problem?

Thanks
Line 21: we want to accumulate into a double (not int).
1
2
// return  sqrt(std::accumulate(auxiliary.begin(), auxiliary.end(), 0 ));
return  std::sqrt(std::accumulate(auxiliary.begin(), auxiliary.end(), 0.0));


And comment out line 19: // auxiliary.shrink_to_fit();
It doesn't do anything other than potentially degrade performance.

Also, need to #include <cmath> and <numeric>
Excellent JLBorges!

Thank you very much!
Topic archived. No new replies allowed.