Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
VectorNormFn
//g++ 7.4.0 //implement a norm function so that if v is a vector then v.norm() would return the square root of v*v //this code is created by Rezaul Hoque on September 10,2021;contact: jewelmrh@yahoo.com //note: codes shared by Rezaul Hoque on rextester are not for sale; they are created and shared to facilitate the algorithm learning process; many like Hoque use this platform to practice programming ;Rezaul hopes his contribution helps others to fine tune their learning; #include <iostream> #include <cmath> class Vector { friend std::ostream& operator<<(std::ostream &, const Vector &);//stream extraction operator friend std::istream& operator>>(std::istream &, Vector &);//stream insertion operator friend Vector operator+(const Vector &, const Vector&);//binary addition operator friend Vector operator-(const Vector &, const Vector&);//binary subtraction operator public: Vector (int ,double );//default constructor Vector (const Vector &);//copy constructor ~Vector();//destructor const Vector & operator=(const Vector &);//assignment operator double& operator[](int) const;//subscript operator Vector norm(); int size; double * data; }; std::ostream& operator<<(std::ostream& ostr,const Vector& v) { int l; ostr<<"( "; for(l=0;l<v.size-1;l++){ ostr<<v[l]<<","; if((l+1)%8 == 0) std::cout<<"\n"; } return ostr<<v[l]<<")\n"; } std::istream& operator>>(std::istream& istr,const Vector& v) { for(int l=0;l<=v.size-1;l++) { std::cout<<l<<":"; istr>>v[l]; } return istr; } Vector::Vector(int sz=1,double t=0.0): size(sz) { data = new double[size]; for(int l=0;l<size;l++) data[l]=t; } Vector:: Vector(const Vector & v): size(v.size) { data = new double[v.size]; for(int l=0;l<v.size;l++) data[l]=v.data[l]; } Vector::~Vector() { delete [] data; data = NULL; size=0; } const Vector& Vector::operator=(const Vector & v) { if(&v != this) { delete [] data; size = v.size; data = new double[size]; for(int l=0;l<size;l++) data[l]=v.data[l]; } return *this; } double& Vector:: operator[](int I) const { return data[I]; } Vector operator+(const Vector & v,const Vector& w) { Vector z(4,0.0); for(int l=0;l<z.size;l++){ z.data[l] = v.data[l] + w.data[l];} return z; } Vector operator-(const Vector & v,const Vector& w) { Vector z(4,0.0); for(int l=0;l<z.size;l++){ z.data[l] = v.data[l] - w.data[l];} return z; } Vector Vector:: norm() { Vector z(4); for(int l=0; l<size; l++) z.data[l] +=sqrt(data[l]*data[l]); return z; } int main() { Vector vec1(4,3.0),vec2(4,4.0),vec3(4); double b=2.0; vec3=vec1+vec2; std::cout<<" vec3:\n"; std::cout<<vec3; std::cout<<"square root of vec2*vec2:\n"<<vec2.norm(); return 0; }
run
|
edit
|
history
|
help
0
articulation points and bridges
quickselect
PriorQ
const_cast
Synchro#3
pointconcat
Graph DFS
Web Browser History - DLL
Subset sum
Reverse factorial