In: Computer Science
In C++
1.Create a class Point which has a template parameter of the type of internal data, T, and a template parameter for the dimension of the Point(2D, 3D etc.). Store a statically allocated, internal array of type T with dimension n. Ensure to include any constructer(s),destructors, getters or setters you might need. (10 points)
2.Create a template function which computes the Euclidean distance between 2 points. (6 points)
3.Instantiate two Point<double, 3> and compute their distance. Instantiate two Point<int, 2> and compute their distance.(4 points)
#include <iostream>
#include <cstdarg>
#include <cmath>
using namespace std;
template <class T, int n>
class Point
{
private:
T arr[n];
public:
// Constructor
Point(...)
{
//cout<<"\n Constructor called \n";
va_list ap;
va_start(ap, n);
for(int i=0; i<n; i++)
{
arr[i] =va_arg(ap, T);
}
va_end(ap);
}
// For debugging
void print()
{
cout<<"\n Point: values \n";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
}
// Destructor
~Point()
{
//cout<<"\n deleting \n";
delete[] arr;
//cout<<"\n deleted\n";
}
// Setter: changing whole value of a Point
void setPoint(...)
{
//cout<<"\n Set point called \n";
va_list ap;
va_start(ap, n);
for(int i=0; i<n; i++)
{
arr[i] =va_arg(ap, T);
}
va_end(ap);
}
//Getter: get whole Point , as a pointer to the internal
"arr"
T* getPoint()
{
return arr;
}
//Setter: set a particular dimension value
void setDimensionValue(long unsigned int dim, T val )
{
if ( dim>n ) cout<<"\n The dimension does not exist for
this point \n";
else arr[dim-1] = val;
}
//Getter: get a particular dimension value
T getDimensionValue(long unsigned int dim)
{
if (dim> n){
cout<<"\n The dimension does not exist for this point. \n
";
return -9999999999999999999999;
}
else return arr[dim-1];
}
};
// function for calculating Eucledian distance
template <class T, int n>
T distance(Point<T, n> p1, Point<T, n> p2)
{
T dist;
for(int i=1; i<=n; i++){
T tmp = p1.getDimensionValue(i) - p2.getDimensionValue(i);
dist += tmp*tmp;
}
return sqrt(dist);
}
int main()
{
Point<double, 3> p1(1.0 , 3.5, 4.5), p2(3.4, 5.6,
2.3);
cout<<"\n Distance between 3d points p1 and p2 is:
"<<distance<double, 3>(p1, p2) <<"\n";
Point<double, 2> p3(1.2, 6.7), p4(2.4, 9.1);
cout<<"\n Distance between 2d points p3 and p4 is:
"<<distance<double, 2>(p3, p4) <<"\n";
return 0;
}