Skip to content

Instantly share code, notes, and snippets.

@theoctober19th
Created November 17, 2019 14:46
Show Gist options
  • Save theoctober19th/d5f6a58025855f98b33d5f34b092d06a to your computer and use it in GitHub Desktop.
Save theoctober19th/d5f6a58025855f98b33d5f34b092d06a to your computer and use it in GitHub Desktop.
/*
Create a class template Vector with a type parameter T which holds an array of type T. Also, include constructor to initialize the objects, a function to calculate scalar product of two two vectors by overloading '*' operator so that statements like v1 * v2 are permissible.
Write a main function to test the above class template and find the scalar product of following pairs of vectors. {1, 2, 3}, {4, 5, 6} and {2.5, 3.5, 4.5}, {1.5, 2.5, 3.5}.
*/
#import <iostream>
using namespace std;
template <typename T>
class Vector{
private:
T arr[3];
public:
Vector(T arr[3]){
for(int i=0; i<3; i++){
this->arr[i] = arr[i];
}
}
T operator * (Vector<T> const &vec){
T sum = 0;
for(int i=0; i<3; i++){
sum += this->arr[i]*vec.arr[i];
}
return sum;
}
void display(){
cout << arr[0] << ' ' << arr[1] << ' ' << arr[2];
}
};
int main(){
int a1[] = {1, 2, 3};
Vector<int> v1 = Vector<int>(a1);
int a2[] = {4, 5, 6};
Vector<int> v2 = Vector<int>(a2);
double a3[] = {2.5, 3.5, 4.5};
Vector<double> v3 = Vector<double>(a3);
double a4[] = {4.5, 5.5, 6.5};
Vector<double> v4 = Vector<double>(a4);
int res1 = v1 * v2;
double res2 = v3 * v4;
cout << "Result 1: " << res1 << endl;
cout << "Result 2: " << res2;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment